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");
        var speed=10;
        document.onkeydown=function(event){
            
            if(event.ctrlKey){
                speed=40;   //按住ctrl移动速度改变
            }else{
                speed=10;
            }
//            //左上右下对应编码37-40
//            switch(event.keyCode){
//                case 37:
////                    alert("向左");
//                    d01.style.left=d01.offsetLeft-speed+"px";
//                    berak;
//                case 38:
////                    alert("向上");
//                    d01.style.top=d01.offsetTop-speed+"px";
//                    berak;
//                case 39:
////                    alert("向右");
//                    d01.style.left=d01.offsetLeft+speed+"px";
//                    berak;
//                case 40:
////                    alert("向下");
//                    d01.style.top=d01.offsetTop+speed+"px";
//                    berak;
//                
//            }
            d=event.keyCode;
            e=event.ctrlKey;
        }
                //使松开停止移动
        document.onkeyup=function(){
            d=0;//
        }
        //来干掉按住移动不连贯(浏览器默认的按住第二下后才连贯),所有要放到document.onkeydown外面来
        
        
        var timer=setInterval(function(){
            //左上右下对应编码37-40
            switch(d){
                case 37:
//                    alert("向左");
                    d01.style.left=d01.offsetLeft-speed+"px";
                    berak;
                case 38:
//                    alert("向上");
                    d01.style.top=d01.offsetTop-speed+"px";
                    berak;
                case 39:
//                    alert("向右");
                    d01.style.left=d01.offsetLeft+speed+"px";
                    berak;
                case 40:
//                    alert("向下");
                    d01.style.top=d01.offsetTop+speed+"px";
                    berak;
                
            }
        },30);
        
    </script>
</html>

 

JavaScript 键盘流畅移动div

上一篇:android studio 编译 Android dependency has different version


下一篇:[双指针] leetcode 42 Trapping Rain Water