方向键控制圆球运动(简易)(js)
Posted 梦里一米七八
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了方向键控制圆球运动(简易)(js)相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{padding:0px; margin:0px; } button{width:100px; height:100px; background:linear-gradient(to left,#FF0,#099); position:fixed;/*弹性布局*/ right:50%; top:50%; text-align:center;/*文本居中,行高,大小,颜色,字体*/ line-height:50px; color:#FFF; font-size:25px; font-family:arial} </style> </head> <body> <button>开始加速</button> <script> var btn = document.getElementsByTagName(‘button‘)[0]; var div = document.createElement(‘div‘); document.body.appendChild(div); div.style.height = ‘100px‘; div.style.width = ‘100px‘; div.style.backgroundColor = ‘red‘; div.style.borderRadius = ‘50%‘; div.style.position = ‘absolute‘; div.style.top = ‘0‘; div.style.left = ‘0‘; var speed = 5; btn.onclick = function(){ speed +=20;} document.onkeydown = function(e){ switch(e.which){ case 38://上 div.style.top = parseInt(div.style.top) - speed + ‘px‘; break; case 40://下 div.style.top = parseInt(div.style.top) + speed + ‘px‘; break; case 37://左 div.style.left = parseInt(div.style.left) - speed + ‘px‘; break; case 39://右 div.style.left = parseInt(div.style.left) + speed + ‘px‘; break; } } </script> </body> </html>
以上是关于方向键控制圆球运动(简易)(js)的主要内容,如果未能解决你的问题,请参考以下文章