停止动画div的settimeout增量

时间:2012-05-01 20:45:52

标签: javascript animation settimeout

我有一个函数可以增加div层位置的css质量,当它达到一定的百分比时,需要它停止向右或向左(取决于图层)。 我试图使用大于运算符的if语句,但似乎不起作用。这是完整的代码:

<html>
<head>
<title>Stelucir</title>
<style>
body {
  background-color: white;
}
#bg-right {
  background-color: black;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 50%;
  right: 0;
  z-index: -1;
}
</style>
<script type="text/javascript">

var header = null; // object
var about = null; // object
var blog = null; // object
var forum = null; // object
var chat = null; // object
var home = null; // object

function doMove() {
  header.style.right = parseInt(header.style.right)+1+'%';
  about.style.left = parseInt(about.style.left)+1+'%';
  blog.style.right = parseInt(blog.style.right)+1+'%';
  forum.style.left = parseInt(forum.style.left)+1+'%';
  chat.style.right = parseInt(chat.style.right)+1+'%';
  home.style.left = parseInt(home.style.left)+1+'%';
  setTimeout(doMove,30); // call doMove in 20msec
}

function init() {
  header = document.getElementById('header');
  about = document.getElementById('about');
  blog = document.getElementById('blog');
  forum = document.getElementById('forum');
  chat = document.getElementById('chat');
  home = document.getElementById('home'); 
  doMove(); // start animating
}

window.onload = init;

</script>
</head>
<body>
<div id="bg-right"></div>
<div id="header" style = "position:absolute;right:25%;font-size:80px;">Stelucir</div>
<div id="about" style = "position:absolute;left:40%;font-  size:40px;top:90px;color:white;">About</div>
<div id="blog" style = "position:absolute;right:40%;font-size:40px;top:130px;">Blog</div>
<div id="forum" style = "position:absolute;left:40%;font-size:40px;top:170px;color:white;">Forum</div>
<div id="chat" style = "position:absolute;right:40%;font-size:40px;top:210px;">Chat</div>
<div id="home" style = "position:absolute;left:40%;font-size:40px;top:250px;color:white;">Home</div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

使用全局布尔值。以true开始,当它到达您想要的任何点时,将其设置为false。在doMove中检查是否为真,如果为false,则返回。

答案 1 :(得分:0)

setTimeout()返回计时器的句柄。然后,您可以在此句柄上调用clearTimeout()来停止计时器。

创建一个全局变量来存储此

var timer = null;
...
function doMove() {
    ...
    timer = setTimeout(...);
}
//somewhere else
clearTimeout(timer);

答案 2 :(得分:0)

我建议使用间隔而不是多个setTimeout调用。同时setInterval和setTimeout都返回一个引用,可以使用clearInterval(ref)或clearTimeout(ref)来停止它们;

这是一个小小的小提琴,可以让一个盒子向右移动并在它出现时停止。

http://jsfiddle.net/JV35w/1/

var elem = document.getElementById('foo'),
    startX = 0,
    endX = 400,
    move = function() {
        elem.style.left = startX + 'px';
        startX += 10;
        if (endX === startX) {
            startX = 0;
            clearInterval(t);
        };
    },
    doMove = function() {
        t = setInterval(move);
    },
    t;

doMove();​

https://developer.mozilla.org/en/DOM/window.setTimeout

https://developer.mozilla.org/en/DOM/window.setInterval