Javascript onkeydown事件只触发一次

Javascript onkeydown event fires only once

本文关键字:一次 onkeydown 事件 Javascript      更新时间:2023-10-27

我的onkeydown函数只触发一次,但我希望它在每次按键时都会触发。按下箭头键时,div对象应该以连续运动的方式移动。

<html>
    <style type="text/css">
      #Rectangle{
        height:40px;
        width:40px;
        background-color:red;   
        position:absolute;   
    }
    </style>
    <script type="text/javascript">
    function start() {
        var box = document.getElementById("Rectangle");
        document.onkeydown = function(e){
            e = e || window.event;
            switch(e.which){
                case 38: //down
                box.style.top -= 10;
                break;
                case 40: //up
                box.style.top += 10;
                break;
            }
        }
    }
    </script>
<body onload="start()">
    <div id="Rectangle"></div>
</body>
</html> 

需要防止parseInt()的NaN结果:

case 38: //down
  box.style.top = ((parseInt(box.style.top, 10) || 0) - 10) + 'px';
  break;
case 40: //up
  box.style.top = ((parseInt(box.style.top, 10) || 0) + 10) + 'px';
  break;

top有单位,您的数学错误

case 38: //down
    box.style.top = ( parseInt(box.style.top, 10) - 10 ) + "px";
    break;
case 40: //up
    box.style.top = ( parseInt(box.style.top, 10) + 10 ) + "px";
    break;

更新
我没有让你有一个js错误,所以你需要做:

<script type="text/javascript">
function start() {
    var box = document.getElementById("Rectangle"), func = function(e){
        e = e || window.event;
        var top = parseInt(box.style.top);
        switch(e.which){
            case 38: //down
            box.style.top = (top - 10) + "px";
            break;
            case 40: //up
            box.style.top = (top + 10) + "px";
            break;
        }
    };
    document.onkeyup = func(e);
}
</script>

尝试这个

document.onkeypress = function() {
   
  //insert your code here
  alert("key pressed!");
 };