js键盘事件

  • keydown:在键盘上按下某个键时触发。如果按住某个键,会不断触发该事件,但是 Opera 浏览器不支持这种连续操作。该事件处理函数返回 false 时,会取消默认的动作(如输入的键盘字符,在 IE 和 Safari 浏览器下还会禁止keypress 事件响应)。
  • keypress:按下某个键盘键并释放时触发。如果按住某个键,会不断触发该事件。该事件处理函数返回 false 时,会取消默认的动作(如输入的键盘字符)。
  • keyup:释放某个键盘键时触发。该事件仅在松开键盘时触发一次,不是一个持续的响应状态。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box {
            width: 400px;
            height: 600px;
            margin: 20px auto 0;
            border: 1px solid;
            position: relative;
        }

        #plane {
            width: 50px;
            height: 50px;
            background: #c40000;
            position: absolute;
            bottom: 0;
            left: 175px;
        }
    </style>
</head>
<body>
    <div id="box">
        <div id="plane"></div>
    </div>
</body>
</html>
<script>
    //onkeydown,onkeyup,onkeypress(系统按键无法得到识别),
    // document.onkeypress = function (event) {
    //     console.log(event.keyCode)
    // }
    var plane = document.getElementById('plane')
    var box = document.getElementById('box')
    document.onkeydown = function (event) {
        if (event.keyCode == 37) {
            // plane.style.left = plane.offsetLeft - 10 + 'px'
            // if (plane.offsetLeft <= 0) plane.style.left = 0
            plane.style.left=plane.offsetLeft>0?plane.offsetLeft - 10 + 'px'
        }//左移
        if (event.keyCode == 39) {
            plane.style.left = plane.offsetLeft + 10 + 'px'
            if (plane.offsetLeft >= box.offsetWidth - plane.offsetWidth) {
                plane.style.left = box.offsetWidth - plane.offsetWidth + 'px'
                plane.style.left=plane.offsetLeft>0?
            }
        }//右移
    }
</script>

 

posted @ 2021-12-26 23:02  仙女会长高  阅读(145)  评论(0)    收藏  举报