打字小游戏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{margin: 0;padding: 0;}
        div{font-size: 60px;position: absolute;}
    </style>
</head>
<body>
    <h2 id="score">得分:0</h2>
</body>
</html>
<script>
var timer=null;
setInterval(function(){
    var div=document.createElement("div");
    var n=String.fromCharCode(parseInt(65+Math.random()*26));
    div.innerText=n;
    div.style.top=0;
    div.style.left=parseInt(200+Math.random()*900)+"px";
    document.body.appendChild(div);
    move(div)
},1000)                                              //设置再页面顶部随机出现字母

function move(obj){
    setInterval(function(){
        var speed=2;
        if(obj.offsetTop>500){
            obj.remove();
        }
        obj.style.top=obj.offsetTop+speed+"px";        
    },30)
}                                                 //设置往下掉的速度 每30MS下掉2PX
var oScore=document.getElementById("score");
var num=0;
document.onkeypress=function(e){
    var aDiv=document.getElementsByTagName("div")
    var e=e||event;
    var code=e.keyCode||e.which;
    for(i=0;i<aDiv.length;i++){
        var code1=aDiv[i].innerText.charCodeAt(0);
        if(code1==code){
            num++;
            aDiv[i].remove();
            oScore.innerText="得分"+num;
            break;
        }
    }
}
</script>

猜你喜欢

转载自www.cnblogs.com/ngdty/p/9487730.html