2

这是我的 Javascript 函数

    <script type="text/javascript">
    var foo = null; // object
    function doMove() {
      foo.style.left = parseInt(foo.style.left)+1+'px';
      setTimeout(doMove,0); // call doMove in 20msec
      document.getElementById("foo").innerHTML = foo.style.left;
    if(foo.style.left=='100px'){
     alert(foo.style.left);
    }}
    function init() {
      foo = document.getElementById('foo'); // get the "foo" object
      foo.style.left = '0px'; // set its initial position to 0px
      doMove(); // start animating
    }
    window.onload = init;
    </script>
    <div id="foo" style="width:100px;background:#99ccff;position: relative;">I am moving box</div>
4

5 回答 5

1

检查您是否<div>已达到所需的端点(例如 100px),如果是,则不再调用该setTimeout()函数:

function doMove() {
  foo.style.left = parseInt(foo.style.left)+1+'px';
  document.getElementById("foo").innerHTML = foo.style.left;
  if(foo.style.left=='100px'){
    alert("Finished");
  } else {
    setTimeout(doMove,20); // call doMove in 20msec
  }
}
于 2012-12-24T09:30:09.037 回答
1

在这里,我为您创建了jsfiddle。看css:

#foo { left: 100px!Important; }​
于 2012-12-24T09:31:50.447 回答
1

这是一个带有停止按钮的示例:

单击停止时,设置一个标志以指示您希望动画停止。在触发下一阶段动画之前检查此标志。

JS:

var foo = null; // object
var bAnimate = true;
function doMove() {
  foo.style.left = parseInt(foo.style.left)+1+'px';
  if (bAnimate) {
      setTimeout(doMove,0); // call doMove in 20msec
  }
  document.getElementById("foo").innerHTML = foo.style.left;
if(foo.style.left=='100px'){
 alert(foo.style.left);
}}
function init() {
  foo = document.getElementById('foo'); // get the "foo" object
  foo.style.left = '0px'; // set its initial position to 0px
  doMove(); // start animating
}
function stop() {
    bAnimate = false;
}
    window.onload = init;​

HTML:

<div id="foo" style="width:100px;background:#99ccff;position: relative;">I am moving box</div>
<input type="button" onclick="stop();" value="stop" />

​</p>

于 2012-12-24T09:32:09.427 回答
1

嗯...这行得通吗?

  function doMove() {
      foo.style.left = parseInt(foo.style.left)+1+'px';
      if (!stop) setTimeout(doMove, 0); // if stop is false then call doMove in 20msec
      document.getElementById("foo").innerHTML = foo.style.left;
    if(foo.style.left=='100px'){
      alert(foo.style.left);
    }
  }
于 2012-12-24T09:32:44.727 回答
1

你去吧,尽管我不鼓励这种模拟动画的方式。

function getLeftPx() {
  console.log(left+"px");
  return left + "px";
}

function init() {
  window.left = 0;

  var foo = document.getElementById('foo'); // get the "foo" object
  foo.style.left = getLeftPx(); // set its initial position to 0px
  doMove(); // start animating
}
window.onload = init;

function doMove() {

  window.moveInterval = setInterval( function() {
    left++;
    foo.style.left = getLeftPx();
    foo.innerHTML = left;

    if( left == 100 ) {
      clearInterval( moveInterval );
    }
  }, 20 );
}
于 2012-12-24T09:37:20.367 回答