zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    剑指offer——最小的K个数和数组中第K大的元素
    Leetcode刷题指南链接整理
    160. Intersection of Two Linked Lists
    100. Same Tree
    92. Reverse Linked List II
    94. Binary Tree Inorder Traversal
    79. Word Search
    78,90,Subsets,46,47,Permutations,39,40 DFS 大合集
    0x16 Tire之最大的异或对
    0x16 Tire
  • 原文地址:https://www.cnblogs.com/huanghuali/p/8442596.html
Copyright © 2011-2022 走看看