javascript按鍵盤上/右/下/左箭頭加速運動
阿新 • • 發佈:2018-02-11
var ali meta spa 鍵盤 end eat tag order
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>javascript加速運動</title> </head> <body> <button style="width:80px; height:40px; line-height:40px; text-align:center; background:linear-gradient( to left ,#999,#d96972,#cc1233,#d96972); position:fixed; top:200px; left:200px;border:0">加速</button> <script type="text/javascript"> var btn = document.getElementsByTagName(‘button‘)[0]; //創建一個div var div = document.createElement(‘div‘); document.body.appendChild(div); div.style.width=‘100px‘; div.style.height=‘100px‘; div.style.backgroundColor=‘red‘; div.style.position=‘absolute‘; div.style.left=‘0‘; div.style.top=‘0‘; var speed = 5; btn.onclick=function(){ speed++; } console.log(‘速度‘+speed); //onkeydown 事件會在用戶按下一個鍵盤按鍵時發生。 document.onkeydown = function(e){// console.log(e)//打印e就知道以下數字的由來 switch (e.which) { //向上 case 38: div.style.top = parseInt(div.style.top) - speed + ‘px‘; break;//來阻止代碼自動地向下一個 case 運行 //向下 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>
javascript按鍵盤上/右/下/左箭頭加速運動