导航

js onkeydown事件连续按键会卡顿一下

Posted on 2017-03-28 21:59  _兮夜  阅读(1379)  评论(0)    收藏  举报

刚看完个视频说是因为微软为了照顾特殊人士而实现的功能,避免重复按出两个字母,连续按键会卡顿一下。所以本人写了个解决代码如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         #div1 {
 8             width: 100px;
 9 height: 100px;
10 background: #CCC;
11 position: absolute;
12 }
13     </style>
14     <script>
15 window.onload = function () {
16             var oDiv = document.getElementById("div1");
17 var direction = {left: false, top: false, right: false, bottom: false};   //上下左右
18 
19 setInterval(function () {
20                     if (direction.left) {
21                         oDiv.style.left = oDiv.offsetLeft - 10 + 'px';
22 } else if (direction.top) {
23                         oDiv.style.top = oDiv.offsetTop - 10 + 'px';
24 } else if (direction.right) {
25                         oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
26 } else if (direction.bottom) {
27                         oDiv.style.top = oDiv.offsetTop + 10 + 'px';
28 }
29                 }
30                 , 50);
31 
32 document.onkeydown = function (ev) {
33                 var oEvent = ev || event;
34 //← 37 ↑38 →39 ↓40
35 switch (oEvent.keyCode) {
36                     case 37:
37                         direction.left = true;
38 break;
39 case 38:
40                         direction.top = true;
41 break;
42 case 39:
43                         direction.right = true;
44 break;
45 case 40:
46                         direction.bottom = true;
47 break;
48 }
49 
50                 document.onkeyup=function(){
51                     direction = {left: false, top: false, right: false, bottom: false};
52 }
53             }
54         }
55     </script>
56 </head>
57 <body>
58 <div id="div1"></div>
59 </body>
60 </html>