JS代码练习之键盘事件

今天看了网上的一个教学视频,感觉还不错,又把之前学的js基础复习了一点(已经半学期没碰了)。
下面附上代码吧

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>键盘事件联系</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        html{
            height: 100%;
        }
        body{
            height: 100%;
            background: url('images/bg.jpg');
            background-size: 100% 100%;
        }
        #site{
            position: relative;
            height: 100%;
        }
        img{
            position: absolute;
            width: 200px;
            height: 300px;
            bottom: 50px;
        }

    </style>
</head>
<body>
    <div id="site">
        <img src="images/YAGAMI/stand.gif" id="MC">
    </div>  
</body>
    <script type="text/javascript">
    var imgObj=document.getElementById("MC");
    var left=0;
    var Game=new game(imgObj);
    document.onkeydown=key;
    function key(e){
        var e=e||window.event;
        Game.keydown(e.keyCode);
        this.onkeyup=function(){
            Game.keyup();
            this.onkeydown=key;
        }
        document.onkeydown=null;
    }
    function game(obj){
        this.left=0;
        this.timer=null;
        this.active={
            "39":function(){
                obj.src="images/YAGAMI/advance.gif";
                this.timer=setInterval(function(){
                    this.left+=5;
                    obj.style.left=this.left + "px";
                }.bind(this),1000/60);
                //bind()方法低版本浏览器不支持。
            },
            "37":function(){
                obj.src="images/YAGAMI/retreat.gif";
                this.timer=setInterval(function(){
                    this.left-=5;
                    obj.style.left=this.left+"px";
                }.bind(this),1000/60);
            },
            "40":function(){
                obj.src="images/YAGAMI/7490881c38cfba5ef724e4ba.gif";
            },
            "stop":function(){
                obj.src="images/YAGAMI/stand.gif";
            }
        };
    }
    game.prototype.keydown=function(keyCode){
        for(var key in this.active){
            if(key==keyCode){
                this.active[key].call(this);
            }
        }
    }
    game.prototype.keyup=function(){
        clearInterval(this.timer);
        this.active.stop();
    }
    </script>
</html>

代码中所用到的图片有

retreat.gif
stand.gif
advance.gif
7490881c38cfba5ef724e4ba.gif
bg.jpg

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值