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>
太棒了!它非常完美!感謝setInterval鏈接,我會檢查一下。祝你有美好的一天! – madube94