0
点赞
收藏
分享

微信扫一扫

事件(event)练习——键盘事件

安七月读书 2022-04-14 阅读 65

键盘事件:一般绑定一些可以获得焦点的对象(如input)或者document

  1. onkeydown, 键盘按下,一直按着泽时间会一直触发,第一次和第二次之间间隔时间稍微长一点,这是为了防止误触误操作
  2. onkeyup:键盘放开

keyCode:按键编码

  1. altKey
  2. ctrlKey
  3. shiftKey

练习1:

<!DOCTYPE html>
<html>

<head>
    <script>
        window.onload = function () {
            document.onkeydown = function (event) {
                event = event || window.event;
                //判断是否同时按下y和ctrl
                if (event.keyCode === 89 && event.ctrlKey) {
                    alert("y and ctrl are pressed");
                }
            }

            var input = document.getElementsByTagName("input")[0];
            input.onkeydown = function (event) {
                event = event || window.event;
                if (event.keyCode >= 48 && event.keyCode <= 57) {
                    //在文本框中输入内容,属于onkeydown的默认行为
                    //如果onkeydown取消默认行为, 则输入内容不会出现在文本框中
                    return false;
                }
            }
        }
    </script>
</head>

<body>
    <input type="text">
</body>
</html>

练习2: 键盘操作移动box

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf8">
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            position: absolute;

        }
    </style>
    <script>
        window.onload = function () {
            document.onkeydown = function (event) {
                event = event || window.event;
                var speed  = 10;
                //加速
                if (event.ctrlKey){
                    speed = 50;
                }
                var box = document.getElementById('box');
                switch (event.keyCode) {
                    case 37:
                        box.style.left = box.offsetLeft - speed + 'px';
                        break;
                    case 38:
                        box.style.top = box.offsetTop - speed + 'px';
                        break;
                    case 39:
                        box.style.left = box.offsetLeft + speed + 'px';
                        break;
                    case 40:
                        box.style.top = box.offsetTop + speed + 'px';
                        break;
                }

            }
        }
    </script>
</head>

<body>
    <div id="box"></div>
</body>

</html>
举报

相关推荐

0 条评论