如果声明为真,则Javascript按键保持跟踪直至秒

时间:2018-02-16 06:18:27

标签: javascript

如果声明为真,我如何成功地使按键保持跟踪直至第二。

这是我的剧本:

document.onkeydown = KeyPressed;

var TestLeftPos = 5;
var Test2LeftPos = 0;

function KeyPressed(k) {

    var TestLeftPosTrack = 0;

    var LeftBtn = 37;
    var RightBtn = 39;
    var UpBtn = 38;
    var DownBtn = 40;

    if (k.keyCode == RightBtn) {

        if (TestLeftPosTrack == 40) {
            Test2LeftPos = Test2LeftPos - 0.5;
            document.getElementById("TestTwo").style.left = Test2LeftPos + "vw";
        }

        else if !(TestLeftPosTrack == 40) {

        TestLeftPos = TestLeftPos + 0.5;
        TestLeftPosTrack = TestLeftPosTrack + 0.5;
        document.getElementById("Test").style.left = TestLeftPos + "vw";

        }

    }

}

问题是,当单击右键时,它应该继续执行else语句,直到原始if语句最终正确。如果它是正确的,它应该立即停止执行else语句并开始执行原始的if语句,而是只是将else语句一直带出,而不管原始if语句当前是否为真。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果你想将TestLeftPos和TestLeftPosTrack增加到40,你应该循环。

编辑:至于for或while循环阻止事件循环和callstack,它们可以被视为反模式,因为我们正在响应事件。 相反,window.setInterval(函数,时间)更合适,这要归功于它的异步特性。

document.addEventListener('onkeydown', KeyPressed);
// in case you want to break loop if key up
var breakLoop = false;
document.addEventListener('onkeyup', function(event) {
  console.log('up');
  breakLoop = true;
});

var TestLeftPos = 5;
var Test2LeftPos = 0;

function KeyPressed(k) {
  console.log('down');
  var TestLeftPosTrack = 0;

  var LeftBtn = 37;
  var RightBtn = 39;
  var UpBtn = 38;
  var DownBtn = 40;

  var test1 = document.getElementById("Test");

  if (k.keyCode === RightBtn) {
    // set the interval
    var id = window.setInterval(() => {
      if (!breakLoop && TestLeftPosTrack < 40) {
        // setting a global variable can cause bugs
        // if a second interval is called before the original interval was cleared
        // you could scope the variable properly or
        // store it in a map with the interval id as the key
        // eg.: testLeftPosMap[id] += 0.5;
        TestLeftPos = TestLeftPos + 0.5;
        TestLeftPosTrack = TestLeftPosTrack + 0.5;
        test1.style.left = TestLeftPos + "vw";
      } else {
        window.clearInterval(id);
        Test2LeftPos = Test2LeftPos - 0.5;
        document.getElementById("TestTwo").style.left = Test2LeftPos + "vw";
      }
   }, 1);
}