使用onkeydown javascript移动div

时间:2014-04-14 00:09:26

标签: javascript events onkeydown

我正在尝试用箭头键(37& 39)移动我的div并按空格键让div显示在onkeyd并消失onkeyup。 但问题是:当我按下空格键时,我希望div继续移动。现在,当我这样做时,div停止移动。

我认为把钥匙放在一个阵列中会起作用,但事实并非如此,你有建议帮助我吗? :)

代码必须是javascript。

var keysPressed = new Array();
window.onkeydown = keyDownHandler;
window.onkeyup = keyUpHandler;

function keyDownHandler(e){
    var s="";
    keysPressed[e.which] = true;
    Key = window.event.keyCode;
    s+=Key+" activee:" + keysPressed[e.which];
    updateKeys();
    document.getElementById("moveDiv").innerHTML  = s;
}

function keyUpHandler(e){
     s="";
     keysPressed[e.which] = false;
     Key = window.event.keyCode;
     s+=Key+" activee:" + keysPressed[e.which];
     updateKeys();
     document.getElementById("moveDiv").innerHTML  = s;
}
    var left=0;
    var top = 0;
function updateKeys(){
    if(keysPressed[39]){
        document.getElementById("moveDiv").style.left = left + 10+"px";
        left += 10;
    }
    if(keysPressed[37]){
        document.getElementById("moveDiv").style.left = left -10+"px";
        left-=10;
    }
    if(keysPressed[32]){
        document.getElementById("show").style.display = "block";
    }
    if(!keysPressed[32]){
        document.getElementById("show").style.display = "none";
    }

}

HTML:

<div style="position:absolute;" id="moveDiv"></div>
<div style="position:absolute; 
                left:500px; 
                top:500px; 
                display: none;" id="show">Pressed spacebar</div>

1 个答案:

答案 0 :(得分:1)

这是你想要达到的目标吗?

Fiddle

function updateKeys() {
    if (keysPressed[0])
        left -= speed;
    if (keysPressed[2])
        left += speed;
    if (keysPressed[1])
        top -= speed;
    if (keysPressed[3])
        top += speed;

    document.getElementById("moveDiv").style.left = left + "px";
    document.getElementById("moveDiv").style.top = top + "px";
    if (spacePressed)
        document.getElementById("show").style.display = "block";
    else
        document.getElementById("show").style.display = "none";
}

setInterval(updateKeys, 1);

Read about setInterval if you are not familiar with it

它基本上设置一个函数来运行每隔所说的毫秒,在这种情况下每1毫秒执行一次函数updateKeys