【问题标题】:else if not working in KeyCode events javascript否则,如果在 KeyCode 事件 javascript 中不起作用
【发布时间】:2022-02-09 22:26:21
【问题描述】:

我试图让我的角色向左和向上移动,我认为 jump()slideLeft() 函数工作正常,问题出在 controller(e) 函数 (else if (e.KeyCode===37)) 中。第一个功能可用,但无法访问第二个条件功能。另外,我想在我做一个slideRight()类似的函数之后让网格变成实心的,所以如果我的角色在上面跳跃,平台会支撑这个正方形。有人对我的任何一个问题有任何想法吗?

代码sn-p:

var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;


function jump() {
  if (isJumping) return
  let timerUpId = setInterval(function() {
    if (bottom > 250) {
      clearInterval(timerUpId);

      let timerDownId = setInterval(function() {
        if (bottom < 0) {
          clearInterval(timerDownId);
          isJumping = false;
        }
        bottom -= 5;
        square.style.bottom = bottom + 'px';
      }, 20)
    }
    isJumping = true;
    bottom += 30;
    square.style.bottom = bottom + 'px';
  }, 20)
}

function slideLeft() {
  console.log('da');
  isGoingLeft = true;
  leftTimerId = setInterval(function() {
    left -= 5;
    square.style.left = left + 'px';
  }, 20)
}

function controller(e) {
  if (e.keyCode === 32)
    jump();
  else if (e.KeyCode === 37)
    slideLeft();
}

document.addEventListener('keydown', controller);
.grid {
  position: absolute;
  background-color: chartreuse;
  height: 20px;
  width: 500px;
  bottom: 100px;
  left: 100px;
}

.square {
  position: absolute;
  background-color: darkblue;
  height: 100px;
  width: 100px;
  bottom: 0px;
  left: 150px;
}

`
<div class="grid"></div>
<div class="square"></div>

【问题讨论】:

标签: javascript html css if-statement solid


【解决方案1】:

编辑: 有一个错字: 您第二次编写 KeyCode

function controller(e) {
    if(e.keyCode===32) {
        jump();
    }
    else if(e.keyCode===37) {
        slideLeft();
    }
}

我不太明白你的问题的第二部分是什么意思。如果您希望角色能够在方块上跳跃,则必须实现碰撞检测。像这样的:

if ( isNotOnGround() ) { 
    fall() 
}

【讨论】:

  • 不,括号是可选的,当条件通过时只执行一条语句。
  • 感谢您的指出,我不知道。但是您的代码中有错字,请参阅我的编辑。
  • 大括号可选,但没有分号终止语句 没有大括号对我来说会使代码的可读性降低stackoverflow.com/q/4797286/125981
猜你喜欢
  • 2016-06-02
  • 2015-11-19
  • 1970-01-01
  • 2020-12-04
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多