Home > Web Front-end > JS Tutorial > Keyboard control implemented in js that feels very smooth (with inertia)_javascript skills

Keyboard control implemented in js that feels very smooth (with inertia)_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 19:12:08
Original
1444 people have browsed it

Very smooth keyboard control (with inertia)


[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> var keyCache = []; var isCache = false; var cacheNum = 0; document.onkeydown = insertKey; document.onkeyup = function(){if(!isCache && event.keyCode>=37&& event.keyCode<=40) keyCache.length = 0;} function insertKey(){ var kc = event.keyCode; if(kc>=37 && kc<=40){ if(kc!=keyCache[keyCache.length-1]){ keyCache.length = 0; keyCache.push(kc,kc,kc,kc,kc,kc) //保证流畅多注入6个 isCache = true; } keyCache.push(kc); } } window.setInterval("writeCache()", 50); function writeCache(){ if(keyCache.length==0) return; var kc = keyCache.shift(); switch(kc){ case 37: man.style.left = parseInt(man.style.left) - 5;break; case 38: man.style.top = parseInt(man.style.top) - 5;break; case 39: man.style.left = parseInt(man.style.left) + 5;break; case 40: man.style.top = parseInt(man.style.top) + 5;break; } if(isCache) cacheNum++; if(cacheNum == 5){ isCache = false; cacheNum = 0; } } </script>
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template