javascript按键盘上/右/下/左箭头加速运动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript加速运动</title>
    
</head>
<body>
<button style="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>
原文地址:https://www.cnblogs.com/huanghuali/p/8442596.html