Div 绝对位置脚本 - onkeyup 甚至不会注册



我想用箭头键做一个简单的移动脚本,但是我有一个奇怪的行为:

-如果我按右键,圆圈会快速向右移动

-如果我按短键,脚本会按预期工作

-我假设长时间按右键是在更新函数,并使其以指数方式更新

-我仍然不知道为什么onkeyup甚至在长按后停止注册。

代码是:

var circle = document.createElement("div");
     circle.style.borderRadius = "50%";
     circle.style.width = "100px";
     circle.style.height = "100px";
     circle.style.position = "absolute";
     circle.style.backgroundColor = "#99CC00";
     circle.id = "green_circle";
     document.body.appendChild(circle);
var greenCircle = document.getElementById("green_circle");
//Movement Interval:
var xPosition = 1
function rightMovement(){
    circle.style.left = (xPosition + "px");
    xPosition++;
    console.log("xPosition is: "+xPosition);
}
//Interval Initializers and stoppers -
function moveRight(){
    startRight = setInterval(rightMovement,1);
}  
function stopMovingRight(){
    clearInterval(startRight);
    console.log("onkeyup stop register")
}
//Event Keybinding
document.onkeydown = function(){
    var r = event.keyIdentifier;
    if(r == "Right"){
    moveRight();
    }
}
document.onkeyup = function(){
    var i = event.keyIdentifier;
    if(i == "Right"){
        stopMovingRight();
        console.log(i);
    }
} 

我有js fiddle

按下键时,代码开始多个间隔。使用布尔值检查圆圈是否已经在移动

检查这个FIDDLE

moving=false;
function moveRight(){
  if(!moving){ //Start an interval only if there is none active
    startRight = setInterval(rightMovement,1);
    moving=true;
   }
}
document.onkeyup = function(){
 var i = event.keyIdentifier;
  if(i == "Right"){
    stopMovingRight();
    moving=false; // interval deactivated, start upon next keydown
    console.log(i);
 }
}

您的方法moveRight()被多次触发。这是因为当按下一个键时,onkeydown事件会被触发多次。你可以通过设置一个标志来解决这个问题,这样moveRight()就不会多次触发。

每次调用moveRight(),设置一个时间间隔。我还建议初始化脚本顶部的startRight变量,以确保不会出现任何错误。像这样:

var startRight = null;

最新更新