2014-04-14 80 views
1

我想讓我的div移動箭頭鍵(37 & 39)並按空格鍵讓div出現onkeydown並消失onkeyup。 但事情是:當我按空格鍵時,我希望div繼續移動。現在,當我這樣做時,div停止移動。使用onkeydown移動div javascript

我以爲把鑰匙放在一個數組中會起作用,但它沒有,你有建議來幫助我嗎? :)

該代碼必須在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

難道這就是你想達到什麼目的?

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

+0

太棒了!它非常完美!感謝setInterval鏈接,我會檢查一下。祝你有美好的一天! – madube94