利用键盘事件移动小方块小demo

思路:

  1. 根据键盘的unicode值来判断是键盘上的哪个键

  2. 通过定位利用键盘事件改编方块的top和left值

  3. 通过开启定时器消除长按键盘的首次卡顿情况

html

<div><div>

css

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

js代码

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;
       }
   }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值