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

时间:2017-06-21 03:04:34

标签: javascript jquery html5 css3

我不能让这个方块移动,我没有错误,我不知道为什么。我认为问题源于键盘输入的处理方式或采用的方法。

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

2 个答案:

答案 0 :(得分:0)

您尚未添加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>

答案 1 :(得分:0)

您需要确保调用例程来初始化页面。所以你的脚本应该是:

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

// added these initialisation calls
myMove();
document.onkeyup = myEventHandler;