问题版本代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <html> <head> <title>键盘控制div移动</title> <meta charset= "utf-8" /> <style type= "text/css" > #div1{width:100px;height:100px;background:#ff0000;position:absolute;} </style> <script type= "text/javascript" > window.onload = function (){ var oDiv = document.getElementById( "div1" ); document.onkeydown = function (ev){ var ev = ev || event; var keyCode = ev.keyCode; switch (keyCode){ case 37: oDiv.style.left = oDiv.offsetLeft-10+ "px" ; break ; case 38: oDiv.style.top = oDiv.offsetTop-10+ "px" ; break ; case 39: oDiv.style.left = oDiv.offsetLeft+10+ "px" ; break ; case 40: oDiv.style.top = oDiv.offsetTop+10+ "px" ; break ; } } } </script> </head> <body> <div id= "div1" ></div> </body> </html> |
问题描述:用js的键盘事件控制一个div移动,当按下一个方向键不放,div会先停顿一下,然后才开始持续移动。(原因:系统要区分用户是否连续输入,第一个到第二个之间有一个停顿时间)
解决方案:先开一个定时器,让div一直处于(往4个方向)准备移动的状态(初始4个方向的值都是false,div就保持在原地不动),当按下某个方向键,这个方向的值就改变为true,div就会开始往这个方向移动,松开方向键,这个方向的值就改变为false , div就停止这个方向移动了。
解决版本代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <html> <head> <title>键盘控制div移动,解决停顿问题</title> <meta charset= "utf-8" /> <style type= "text/css" > #div1{width:100px;height:100px;background:#ff0000;position:absolute;} </style> <script type= "text/javascript" > window.onload = function (){ var oDiv = document.getElementById( "div1" ); var timer = null; var left = false; var right = false; var top = false; var bottom = false; setInterval( function (){ if (left){ oDiv.style.left = oDiv.offsetLeft-10+ "px" ; } else if (top){ oDiv.style.top = oDiv.offsetTop-10+ "px" ; } else if (right){ oDiv.style.left = oDiv.offsetLeft+10+ "px" ; } else if (bottom){ oDiv.style.top = oDiv.offsetTop+10+ "px" ; } },50); document.onkeydown = function (ev){ var ev = ev || event; var keyCode = ev.keyCode; switch (keyCode){ case 37: left = true; break ; case 38: top = true; break ; case 39: right = true; break ; case 40: bottom = true; break ; } } document.onkeyup = function (ev){ var ev = ev || event; var keyCode = ev.keyCode; switch (keyCode){ case 37: left = false; break ; case 38: top = false; break ; case 39: right = false; break ; case 40: bottom = false; break ; } } } </script> </head> <body> <div id= "div1" ></div> </body> </html> |