简体   繁体   English

在 JavaScript 中仅工作一次的按键事件

[英]On key up event working only once in JavaScript

I am trying to create a JavaScript game.我正在尝试创建 JavaScript 游戏。 There, I have created a function that whenever we press the right arrow key, the DIV should move to the right.在那里,我创建了一个 function,每当我们按下右箭头键时,DIV 应该向右移动。 When I press it for the first time, it works fine.当我第一次按下它时,它工作正常。 However, when I press it after that, it does not work.但是,当我在那之后按下它时,它不起作用。 Here is the code I have tried so far:这是我到目前为止尝试过的代码:

 <html> <head> <style>.runobj { width: 80px; height: 80px; position: absolute; background-color: #00ff00; top: 0; left: 0; } </style> </head> <body onkeydown="moveObj(event)"> <div class="runobj" id="runobj"></div> <script> function moveObj(event) { var runobj = document.getElementById("runobj"); if (event.keyCode === 37) { runobj.style.left -= 10; } else if (event.keyCode === 39) { runobj.style.left += 10; } } </script> </body> </html>

What am I doing wrong here?我在这里做错了什么? Any help would be appreciated.任何帮助,将不胜感激。 Thankyou!谢谢!

style.left is a string property with a unit (ie: "10px" ). style.left是一个带有单位的字符串属性(即: “10px” )。 To add or take units of it you first need to parse it to a number or use another property (ie: offsetLeft ) and after assign it back with the unit.要添加或获取它的单位,您首先需要将其解析为一个数字或使用另一个属性(即: offsetLeft ),然后将其分配回单位。

 function moveObj(element, event){ console.log('keycode', event.keyCode); //REM: Looking up the same element all the time is not ideal. Maybe pass it instead? var runobj = element || document.getElementById("runobj"); //REM: You need to turn "style.left" into a number var tCurrentLeft = parseFloat(runobj.style.left) || 0; //REM: Just use a switch, since it looks like you are going to implement more key actions switch(event.keyCode){ case 37: //REM: Do not forget to add the unit runobj.style.left = tCurrentLeft - 10 + 'px'; break case 39: //REM: Do not forget to add the unit runobj.style.left = tCurrentLeft + 10 + 'px' }; console.log('left', runobj.style.left) }; //REM: It is better to fully split the javascript from the HTML markup. Also you can just pass the element and avoid lookups. window.addEventListener('keydown', moveObj.bind(this, document.getElementById("runobj")));
 .runobj { width: 80px; height: 80px; position: absolute; background-color: #00ff00; top: 0; left: 0; }
 <body> <div class="runobj" id="runobj"></div> </body>

Modified your code to handle the postfix px for left attribute:修改了您的代码以处理left属性的后缀px

 <html> <head> <style>.runobj { width: 80px; height: 80px; position: absolute; background-color: #00ff00; top: 0; left: 0; } </style> </head> <body onkeydown="moveObj(event)"> <div class="runobj" id="runobj"></div> <script> var _left = 0; function moveObj(event) { var runobj = document.getElementById("runobj"); if (event.keyCode === 37) { _left -= 10; } else if (event.keyCode === 39) { _left += 10; } runobj.style.left = _left + 'px'; } </script> </body> </html>

Make the function recursive so that on every click event it should moved automatically without refreshing it to the initials.使 function 递归,以便在每次单击事件时它应该自动移动,而无需将其刷新为首字母。

After the first modification, the value of the left property is the string '10px'.第一次修改后,left属性的值为字符串'10px'。 So to continue adding values, you need to extract that value before adding a new values, for example:因此,要继续添加值,您需要在添加新值之前提取该值,例如:

runobj.style.left = parseInt(runobj.style.left || 0, 10) + 10;

(The '|| 0' is for the first iteration, because it receives an empty string) ('|| 0' 用于第一次迭代,因为它接收一个空字符串)

// cache the element
var runobj = document.getElementById("runobj");

function moveObj(event) {
  var left = runobj.getBoundingClientRect().left;

  if (event.keyCode === 37) {
    left -= 10;
  } else if (event.keyCode === 39) {
    left += 10;
  }

  runobj.style.left = left + "px";
}

Working example工作示例

We need to convert style.left from String datatype to Number datatype inorder to increment or decrement the value.我们需要将style.left从 String 数据类型转换为 Number 数据类型,以便增加或减少值。

After the first modification, the value of the left property is the string '10px'.第一次修改后,left属性的值为字符串'10px'。

So when you tried to increment style.left by number 10 after the first modification, it becomes 10px10 which is not a valid value for style.left property.That's why it only works for the first time.因此,当您尝试在第一次修改后将style.left增加数字 10 时,它变为10px10 ,这不是style.left属性的有效值。这就是它仅在第一次工作的原因。

var runobj = document.getElementById("runobj");
function moveObj(event) {

  /* Converting the left style value from String type to Number type.
  '|| 0' is for the first iteration, because it receives an empty string */

  var current = parseFloat(runobj.style.left) || 0;
  
  if (event.keyCode === 37) {
        current += 20;
      } else if (event.keyCode === 39) {
        current -= 20;
      }
      // Updating the value
      runobj.style.left = current;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM