javascript - 我有一段代码试图让一个盒子移动,但它不起作用。语言为HTML5,代码如下

标签 javascript jquery html css

我无法得到这个来让正方形移动,我没有得到错误,我也不知道为什么。我认为问题出在键盘输入的处理方式或处理方式上。

<!DOCTYPE html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
</style>
<body>    

<div id ="container">
<div id ="animate"></div>
</div>

<script>
var pos = 0;
function myMove() {
  var elem = document.getElementById("animate");   
  var id = setInterval(frame, 5);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      elem.style.top = pos + 'px'; 
      elem.style.left = pos + 'px'; 
    }
  }
}

function myEventHandler(e) {
    var keyCode = e.keyCode;
    if(keyCode == 37) {
        pos = pos - 1
    }
    if(keyCode = 39) {
        pos = pos + 1
    }
}
</script>    
</body>
</html>    
</body>
</html>

最佳答案

您还没有添加 onkeydown 事件监听器,您还没有调用函数来更新元素的位置,实际上不需要 setInterval 函数来执行此操作。

var pos = 100;
function myMove() {
  var elem = document.getElementById("animate");   
  
    if (pos == 350) {
      clearInterval(id);
    } 
    else {
     
      elem.style.top = pos + 'px'; 
      elem.style.left = pos + 'px'; 
  }
}
function myEventHandler(e){

    var keyCode = e.keyCode;
    if(keyCode == 37){
        pos = pos - 1;
        myMove();
    }
    if(keyCode = 39){
        pos = pos + 1;
        myMove();
        }
}
document.onkeydown = myEventHandler;
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
<div id ="container">
<div id ="animate"></div>
</div>

关于javascript - 我有一段代码试图让一个盒子移动,但它不起作用。语言为HTML5,代码如下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666187/

相关文章:

javascript - 单击文本时在转发器中选择/取消选择复选框

html - float :left problem

javascript - jQuery:int值分割为数组

javascript - JavaScript 中的可观察集合?

javascript - 检测元素是否已停止动量滚动?

javascript - jQuery 手机 : Applying style after reloading content

html - IE9 中的负边距和 float

jquery - Div 在图像上显示单击 jquery

javascript - 页面滚动的原因是什么

javascript - 通过单击 div 启用/禁用所有音效 - javascript