Javascript onkeydown事件只触发一次

时间:2015-02-13 13:50:01

标签: javascript

我的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> 

4 个答案:

答案 0 :(得分:3)

需要防止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;

答案 1 :(得分:2)

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;

答案 2 :(得分:-1)

<强>更新
我没有得到你的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>

答案 3 :(得分:-3)

试试这个

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

相关问题