я хочу вызывать функцию много раз внутри моего кода? - PullRequest
0 голосов
/ 26 марта 2020

Я планирую делать это окно каждый раз, когда нажимаю кнопку, но проблема в том, что он работает впервые, когда я нажимаю s или d, но не работает после этого. Так может ли кто-нибудь помочь мне найти решение моей проблемы?

<!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>

Ответы [ 2 ]

0 голосов
/ 26 марта 2020

Вы пытаетесь выполнить операцию над строкой. Сначала нужно конвертировать в число.

Образец:

<!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>
0 голосов
/ 26 марта 2020

element.style.top и element.style.left являются строками, поэтому ваши операторы по сути говорят:

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

Вместо этого рассмотрим отдельную переменную позицию хранения:

let positionLeft = 20;

...

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