[转载]感觉很流畅的键盘控制(带惯性)
1<body>
2<div id="man" style="position:absolute;width:50px;height:40px;top:200px;left:200px;background:red"></div>
3<button onclick="alert(keyCache.length)">ask</button>
4</body>
5<script>
6var keyCache = [];
7var isCache = false;
8var cacheNum = 0;
9
10document.onkeydown = insertKey;
11document.onkeyup = function(){if(!isCache && event.keyCode>=37&& event.keyCode<=40) keyCache.length = 0;}
12
13function insertKey(){
14 var kc = event.keyCode;
15 if(kc>=37 && kc<=40){
16 if(kc!=keyCache[keyCache.length-1]){
17 keyCache.length = 0;
18 keyCache.push(kc,kc,kc,kc,kc,kc) //保证流畅多注入6个
19 isCache = true;
20 }
21 keyCache.push(kc);
22 }
23}
24
25window.setInterval("writeCache()", 50);
26
27function writeCache(){
28 if(keyCache.length==0) return;
29
30 var kc = keyCache.shift();
31
32 switch(kc){
33 case 37: man.style.left = parseInt(man.style.left) - 5;break;
34 case 38: man.style.top = parseInt(man.style.top) - 5;break;
35 case 39: man.style.left = parseInt(man.style.left) + 5;break;
36 case 40: man.style.top = parseInt(man.style.top) + 5;break;
37 }
38
39 if(isCache) cacheNum++;
40 if(cacheNum == 5){
41 isCache = false;
42 cacheNum = 0;
43 }
44}
45</script>
2<div id="man" style="position:absolute;width:50px;height:40px;top:200px;left:200px;background:red"></div>
3<button onclick="alert(keyCache.length)">ask</button>
4</body>
5<script>
6var keyCache = [];
7var isCache = false;
8var cacheNum = 0;
9
10document.onkeydown = insertKey;
11document.onkeyup = function(){if(!isCache && event.keyCode>=37&& event.keyCode<=40) keyCache.length = 0;}
12
13function insertKey(){
14 var kc = event.keyCode;
15 if(kc>=37 && kc<=40){
16 if(kc!=keyCache[keyCache.length-1]){
17 keyCache.length = 0;
18 keyCache.push(kc,kc,kc,kc,kc,kc) //保证流畅多注入6个
19 isCache = true;
20 }
21 keyCache.push(kc);
22 }
23}
24
25window.setInterval("writeCache()", 50);
26
27function writeCache(){
28 if(keyCache.length==0) return;
29
30 var kc = keyCache.shift();
31
32 switch(kc){
33 case 37: man.style.left = parseInt(man.style.left) - 5;break;
34 case 38: man.style.top = parseInt(man.style.top) - 5;break;
35 case 39: man.style.left = parseInt(man.style.left) + 5;break;
36 case 40: man.style.top = parseInt(man.style.top) + 5;break;
37 }
38
39 if(isCache) cacheNum++;
40 if(cacheNum == 5){
41 isCache = false;
42 cacheNum = 0;
43 }
44}
45</script>