html屏蔽上下左右键控制页面,【案例】使用上下左右键控制元素的移动

使用键盘上下左右键控制小球移动

*{

margin:0;

padding:0;

}

#ball{

width: 200px;

height: 200px;

background: pink;

border-radius: 50%;

position: absolute;

}

//获取元素

var ball = document.getElementById('ball');

//定义小球每次移动的步径

var step = 1;

//定义小球水平、垂直方向移动定时器标志

var runX,runY;

//为使小球运行更流畅,加入水平移动定时器

function moveX(step){

console.log(runX);

if(runX){

return;

}

runX = setInterval(function(){

var newLeft = ball.offsetLeft + step;

var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;

if(newLeft <= 0){

newLeft = 0;

}

if(newLeft >= clientWidth - ball.offsetWidth){

newLeft = clientWidth - ball.offsetWidth;

}

ball.style.left = newLeft + 'px';

},5);

}

//为使小球运行更流畅,加入垂直移动定时器

function moveY(step){

if(runY){

return;

}

runY = setInterval(function(){

var newTop = ball.offsetTop + step;

var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

if(newTop <= 0){

newTop = 0;

}

if(newTop >= clientHeight - ball.offsetHeight){

newTop = clientHeight - ball.offsetHeight;

}

ball.style.top = newTop + 'px';

},5);

}

//键盘按键按下时小球移动

window.onkeydown = function(e){

//兼容性写法

var e = e || window.event;

//使用switch结构判断键盘按下的是哪个键

switch(e.keyCode){

case 37:

moveX(-step);

break;

case 38:

moveY(-step);

break;

case 39:

moveX(step);

break;

case 40:

moveY(step);

break;

}

}

//键盘按键抬起时,小球停止移动

window.onkeyup = function(){

//清除定时器

clearInterval(runX);

runX = undefined;

clearInterval(runY);

runY = undefined;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值