/*
* 使div可以根据不同的方向键向不同的方向移动
* 按左键,div向左移
* 按右键,div向右移
* 37 左
* 38 右
* 39 上
* 40 下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box1{ width: 100px; height: 100px; background: red; position: absolute; } </style> <script type="text/javascript"> /* * 使div可以根据不同的方向键向不同的方向移动 * 按左键,div向左移 * 按右键,div向右移 * 37 左 * 38 右 * 39 上 * 40 下 */ window.onload = function(){ //为document绑定按键按下的事件 document.onkeydown = function(){ console.log(event.keyCode) event = event || window.event; switch(event.keyCode){ case 37: box1.style.left = box1.offsetLeft-10 +"px"; break; case 38: box1.style.left = box1.offsetLeft+10 +"px"; break; case 39: box1.style.top = box1.offsetTop-10 +"px"; break; case 40: box1.style.top = box1.offsetTop+10 +"px"; break; } } } </script> </head> <body> <div id="box1"> </div> </body> </html>
修改版,升级版
由于使用按键不仅要向右移动还要控制速度,会出现卡顿的情况。所以可以使用定时器来控制速度,按键是控制方向。
如下是修改后的代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box1{ width: 100px; height: 100px; background: red; position: absolute; } </style> <script type="text/javascript"> /* * 使div可以根据不同的方向键向不同的方向移动 * 按左键,div向左移 * 按右键,div向右移 * 37 左 * 38 右 * 39 上 * 40 下 * 由于使用按键不仅要向右移动还要控制速度,会出现卡顿的情况。所以可以使用定时器来控制速度,按键是控制方向。 */ //控制移动速度 var speed = 10; //创建一个变量表示方向 var dir = 0; window.onload = function(){ //为document绑定按键按下的事件 setInterval(function(){ switch(dir){ case 37: box1.style.left = box1.offsetLeft-speed +"px"; break; case 38: box1.style.left = box1.offsetLeft+speed +"px"; break; case 39: box1.style.top = box1.offsetTop-speed +"px"; break; case 40: box1.style.top = box1.offsetTop+speed +"px"; break; }},300); document.onkeydown = function(){ event = event || window.event; dir = event.keyCode; if(event.ctrlKey){ //如果按了ctrl,则加快速度,否则减慢速度 speed = 500; }else{ speed = 10; } } document.onkeyup = function(){ dir = 0; } } </script> </head> <body> <div id="box1"> </div> </body> </html>