setInterval代码不起作用

时间:2017-12-07 17:27:51

标签: javascript html

我有这个HTML:

<body onclick = 'myMove(event)'>
    <p>
    <button onclick="myMove(event)">Go Right</button>
    </p>
    <div id ="animate"></div>
    <p id='para'>HI</p>
</body>

这个JavaScript:

function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  let pos = elem.style.marginLeft;

  function frame() {
    if (pos === event.clientX) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.left = pos + 'px';
    }
  }

但是每次运行时,框都会开始,然后移动到我的鼠标位置。有没有办法让它从任何地方进入鼠标位置而不是回到起点?

2 个答案:

答案 0 :(得分:0)

您的代码有两个问题。 1.必须在调用setinterval之前声明函数框架 2.变量idpos不在frame的范围内。所以它们也应该在主函数myMove中全局声明。

function myMove(event) {
    let id;
    let pos;
    let frame = function() {
        if (pos === event.clientX) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.left = pos + 'px';
        }
      }
    let elem = document.getElementById("animate");
    document.getElementById('para').innerHTML = event.clientX;
    let id = setInterval(frame, 5);
    let pos = elem.style.marginLeft;
}

答案 1 :(得分:0)

&#13;
&#13;
<script>
 let pos = null;
function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  if(pos === null){
   pos = elem.style.marginLeft;
  }
 

  function frame() {
    if (pos === event.clientX ) {
      clearInterval(id);
    } else if(pos < event.clientX){
      
      pos++;
      elem.style.left = pos + 'px';
    }
    else{
      pos--;
      elem.style.left = pos + 'px';
    }
  }
 }
</script>

<body onclick = 'myMove(event)'>
    <p>
    <button onclick="myMove(event)">Go Right</button>
    </p>
    <div style='position:relative;' id ="animate">aaa</div>
    <p id='para'>HI</p>
</body>
&#13;
&#13;
&#13;