这是我的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>
答案 0 :(得分: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
}
}
答案 1 :(得分:1)
我在这里为您创建了jsfiddle。看看css:
#foo { left: 100px!Important; }
答案 2 :(得分: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" />
答案 3 :(得分: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);
}
}
答案 4 :(得分:1)
There you go,即使我不鼓励这种模拟动画的方式。
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 );
}