Events using the keyboard to move the small square small demo

Ideas:

  1. The keyboard unicode value to determine which key on the keyboard

  2. By positioning using the keyboard events adaptation box top and left values

  3. Eliminate long press of the keyboard for the first time Caton situation by turning on the timer

html

<div><div>

css

div{
    width:100px;
    height:100px;
    position:absolute;
    background:red;
}

js code

window.onload=function(){
    var div=document.querySelector('div');
    var toLeft=toRight=toTop=toBottom=false;//设置方向变量,后面需要用作判断
    var step=5;//设置移动的步进
    //开启一个定时器
    var timer=setInterval(function(){
        //根据方向变量进行判断
        if(toLeft){
            div.style.left=div.offsetLeft-step+'px';
        }
        if(toRight){
            div.style.left=div.offsetLeft+step+'px';
        }
        if(toTop){
            div.style.top=div.offsetTop-step+'px';
        }
        if(toBottom){
            div.style.top=div.offsetTop+step+'px';
        }
    },30);
    
    //按下方向键时
    document.onkeydown=function(ev){
        console.log(ev.keyCode);//检查方向的unicode
        //左:37 上:38 右:39 下:40
        //用switch语句来判断按下了哪个方向键
        switch(ev.keyCode){
            case 37:toLeft=true;break;
            case 38:toTop=true;break;
            case 39:toRight=true;break;
            case 40:toBottom=true;break;
        }
    }
    
   //松开按键时
   document.onkeyup=function(ev){
       //还原对应松开的值
       switch(ev.keyCode){
            case 37:toLeft=false;break;
            case 38:toTop=false;break;
            case 39:toRight=false;break;
            case 40:toBottom=false;break;
       }
   }

}

Guess you like

Origin www.cnblogs.com/homehtml/p/12488897.html