主要运用js、css、jQuery的基本语法完成。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>打字游戏</title>
<style>
body{
background-image: url(img/dz2.jpg);
background-repeat: no-repeat;
background-size: cover;
margin: 0px;
padding: 0px;
}
#d-bottom{
background-color: cornflowerblue ;
width: 100%;
height: 80px;
position: absolute;
bottom: 0px;
}
.stop{
background-image: url(img/stop.png);
width: 200px;
height: 80px;
background-repeat: no-repeat;
text-align: center;
line-height: 70px;
float: left;
cursor: pointer;
}
#score{
background-image: url(img/fs.png);
background-repeat: no-repeat;
background-size: 200px 300px;
width: 200px;
height: 300px;
position: absolute;
right: 20px;
bottom: 30px;
text-align: center;
line-height: 220px;
font-size: 50px;
}
#lose{
background-image: url(img/sp1.png);
width: 500px;
height: 400px;
background-repeat: no-repeat;
background-size: 500px 400px;
position: absolute;
top: -60%;
left: 350px;
cursor: pointer;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
var arr=[];
var score=0;
function createLetter(){
//根据图片名称搜索名字,
//图片名称根据asii码获取,asii码根据随机数生成。大写字母 A-Z 背后的asii码 是65-90
var key = Math.random()*25+65;
var letter = String.fromCharCode(key);
var img = document.createElement("img");//创建标签
img.setAttribute("src","img/"+letter+".png");//赋值
img.setAttribute("name",letter);
img.style.position="absolute";
var left = Math.floor(Math.random()*1200+50);//随机控制图片生成的位置
img.style.left=left+"px";
document.body.appendChild(img);//写入标签
arr.push(img);
}
function down(){
for(var i=0;i<arr.length;i++){
//使用jQuery获取高度没有px
arr[i].style.top = $(arr[i]).offset().top+20+"px";
if($(arr[i]).offset().top>470){
$(arr[i]).remove();
score--;//给计分板赋值
$("#score").html(score);//写入
if(score<0){
clear();
//jquery动画 3秒执行到top=0
$("#lose").animate({top:"0px"},3000);
}
}
}
}
function start(){
//让失败牌隐藏
$("#lose").css("top","-60%");
//重置记分牌分数
score=0;
$("#score").html(score);
sid = window.setInterval("createLetter()",700);//使用计时器重复生成图片
did = window.setInterval("down()",200);//使用计时器重复掉落图片
}
function clear(){
//清除计时器
window.clearInterval(sid);
window.clearInterval(did);
for(var i=0;i<arr.length;i++){
$(arr[i].remove());
}
}
window.onkeydown=function(e){
var word = String.fromCharCode(e.keyCode);
for(var i=0;i<arr.length;i++){
var letter = $(arr[i].attr("name"));
if(word==letter){
$(arr[i].remove());
score++;
$("#score").html(score);
break;
}
}
}
</script>
</head>
<body>
<div id="lose" onclick="start();"></div>
<div id="d-bottom">
<div class="stop" onclick="start();">启动游戏</div>
<div class="stop">暂停游戏</div>
</div>
<div id="score">0</div>
</body>
</html>