JavaScript 键盘移动div练习

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #d01{
                width: 100px;
                height: 100px;
                background-color: red;
                position: absolute;
            }
        </style>
    </head>
    <body>
        <div id="d01"></div>
    </body>
    <script type="text/javascript">
        /*键盘移动
         * 按左键,d01左移。。。
         */
        var d01=document.getElementById("d01");
        document.onkeydown=function(event){
            //左上右下对应编码37-40
            switch(event.keyCode){
                case 37:
//                    alert("向左");
                    d01.style.left=d01.offsetLeft-10+"px";
                    berak;
                case 38:
//                    alert("向上");
                    d01.style.top=d01.offsetTop-10+"px";
                    berak;
                case 39:
//                    alert("向右");
                    d01.style.left=d01.offsetLeft+10+"px";
                    berak;
                case 40:
//                    alert("向下");
                    d01.style.top=d01.offsetTop+10+"px";
                    berak;
                
            }
        }
    </script>
</html>

猜你喜欢

转载自www.cnblogs.com/wangdongwei/p/11298279.html
今日推荐