JavaScript练习(三)——键盘移动div

tech2024-12-18  4

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box1 { width: 100px; height: 100px; background-color: blueviolet; /** 开启绝对定位 */ position: absolute; } </style> <script> window.onload = function () { var box1 = document.getElementById("box1"); document.onkeydown = function (event) { event = event || window.event; switch (event.keyCode) { case 37: box1.style.left = box1.offsetLeft - 10 + "px"; break; case 39: box1.style.left = box1.offsetLeft + 10+ "px"; break; case 38: box1.style.top = box1.offsetTop- 10 + "px"; break; case 40: box1.style.top = box1.offsetTop + 10 + "px"; break; } console.log(event.keyCode); } } </script> </head> <body > <div id="box1"></div> </body> </html>

注意移动滑块一定要给样式加入绝对定位。

 

使用定时器优化键盘移动div

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box1 { width: 100px; height: 100px; background-color: blueviolet; /** 开启绝对定位 */ position: absolute; } </style> <script> window.onload = function () { var box1 = document.getElementById("box1"); var dir=4; setInterval(function(){ switch (dir) { case 0: box1.style.left = box1.offsetLeft - 10 + "px"; break; case 1: box1.style.left = box1.offsetLeft + 10+ "px"; break; case 2: box1.style.top = box1.offsetTop- 10 + "px"; break; case 3: box1.style.top = box1.offsetTop + 10 + "px"; break; default:break; } },30) document.onkeydown = function (event) { event = event || window.event; switch (event.keyCode) { case 37: dir=0; break; case 39: dir=1; break; case 38: dir=2; break; case 40: dir=3; break; } console.log(event.keyCode); } document.onkeyup=function(){ dir=4; } } </script> </head> <body > <div id="box1"></div> </body> </html>

由于之前写的程序,在div移动时会有卡顿,那么就使用定时器来触发移动效果,使用一个额外变量存储移动方向,这样就不会存在移动卡顿的情况了,而松开按键就停止移动的操作是,检测松开按键的操作,松开时,就直接把方向改变为一个区别于移动的数值,这样就可以停止移动了。

最新回复(0)