我想在我的代码中多次调用一个函数?

i want to call a function many time inside my code?

我计划在每次单击按钮时让这个框移动 但问题是当我单击 sd 时它第一次工作,但之后就不起作用了。 那么有人可以帮助我找到解决问题的方法吗?

<!DOCTYPE html>
<html>

<head>
<style>
 .box {
    position: absolute;
    left: 10px;
    top: 20px;
    width: 20px;
    height: 20px;
    background-color: black;
    border: 1px solid black;
    border-radius: 5px;
}
              </style>
</head>

<body id="bd">

<div class="box"></div>

<script >

document.getElementById('bd').addEventListener('keypress', show);
function show(e){
    let x = e.which;
    if(x == 122){
       // 122 = z
    document.getElementsByClassName('box')[0].style.top -='50px' ;      
     }
     else  if(x == 133){
         // 122 = q
     document.getElementsByClassName('box')[0].style.left -='50px' ; 

    }
     else  if(x == 115){
       // 122 = s
     document.getElementsByClassName('box')[0].style.top +='50px' ; 
    }
     else  if(x == 100){
        // // 122 = d
     document.getElementsByClassName('box')[0].style.left +='50px' ;    
    }
}
</script>
</body>

</html>

element.style.topelement.style.left 是字符串,所以你的陈述本质上是在说

element.style.top = "20px" + "50px";

相反,考虑一个单独的变量存储位置:

let positionLeft = 20;

...

if(x == 115){
    positionLeft += 50;
    document.getElementsByClassName('box')[0].style.top = positionLeft + 'px'; 
}

您正在尝试对字符串执行操作。首先需要进行数字转换。

Sample:

<!DOCTYPE html>
<html>

<head>
  <style>
    .box {
      position: absolute;
      left: 10px;
      top: 20px;
      width: 20px;
      height: 20px;
      background-color: black;
      border: 1px solid black;
      border-radius: 5px;
    }
  </style>
</head>

<body id="bd">
  <div class="box"></div>

  <script>
    const number = (num) => Number(num.split('px')[0])
    const addBy50 = (num) => `${number(num) + 50}px`
    const subtractBy50 = (num) => `${number(num) - 50}px`
    const style = document.getElementsByClassName("box")[0].style
    document.addEventListener("keypress", (e) => {
      let x = e.which;
      const {
        top,
        left
      } = style
      switch (e.which) {
        case 122:
          style.top = subtractBy50(top);
          break;
        case 113:
          style.left = subtractBy50(left);
          break
        case 115:
          style.top = addBy50(top);
          break
        case 100:
          style.left = addBy50(left);
          break
      }
    });
  </script>
</body>

</html>