JS代码练习之键盘事件

来源:互联网 发布:行爱交流软件 编辑:程序博客网 时间:2024/06/13 21:57

今天看了网上的一个教学视频,感觉还不错,又把之前学的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

原创粉丝点击