5推盒子的小例子

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>推盒子</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            position: absolute;
            width: 200px;
            height: 200px;
            background: lightblue;
            margin: 10px auto;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div id="box" style="left: 500px;top:50px;"></div>
<script type="text/javascript">
    var oBox = document.getElementById("box");
    document.onkeyup = document.onkeydown=document.onkeypress=function(e){
        e=e||window.event;
        var curT=parseFloat(oBox.style.top),curL=parseFloat(oBox.style.left);
        if(e.keyCode===37){
            oBox.style.left=curL-1+"px";
            return;
        }
        if(e.keyCode===38){
            oBox.style.top=curT-1+"px";
            return;
        }
        if(e.keyCode===39){
            oBox.style.left=curL+1+"px";
            return;
        }
        if(e.keyCode===40){
            oBox.style.top=curT+1+"px";
        }
    };
    /*
    * //e.keyCode:记录当前按键的编码
     //->左上右下:37.38,39,40
     //->空格:32
     //->回车:13
     // ->回退键(Backspace):8,
     //->删除键:46
     //->shift:16
     //->Ctrl:17
     */
</script>
</body>
</html>

 

posted @ 2016-04-29 17:33  kpengfang  阅读(226)  评论(0编辑  收藏  举报