如何停止动画

时间:2016-10-30 23:43:42

标签: javascript animation

我对编程很新,刚刚开始学习Javascript。我创建了一个个人投资组合,我希望自己的图像从屏幕的一端水平滑动到另一端。我有代码可以让它水平滑动,但我不知道如何阻止它。

我的代码目前看起来像这样:

var move = null;

function doMove() {
    move.style.left = parseInt(move.style.left) + 2 + 'px';
    setTimeout(doMove);
}
function init() {
    move = document.getElementById("myimge");
    move.style.left = "0px";
    doMove();
}
window.onload = init;

我想我应该写一个if语句并调用clearTimeout函数来停止动画,但我无法弄清楚代码。任何援助都会很棒。

2 个答案:

答案 0 :(得分:1)

关键是你要递归地调用doMove(),使用setTimeout()以人眼可感知的帧速率移动元素。要停止递归函数,请引入一个条件来终止它,如下所示:

var move = null;
var body_width = document.body.clientWidth;

function doMove() {
    var rect = move.getBoundingClientRect();

    // end recursion when the element's displacement to the right matches the width of the body element containing it
    if(rect.right >= body_width) {
      return;
    }

    move.style.left = parseInt(move.style.left) + 2 + 'px';
    setTimeout(doMove); // could also use requestAnimationFrame(doMove);
}

function init() {
    move = document.getElementById("myimage");
    move.style.left = "0px";
    doMove();
}

window.onload = init;

Demo

考虑使用CSS transforms而不是修改left / right属性,因为转换效果更好,并且会产生更好的帧速率。

还建议使用requestAnimationFrame代替setTimeout。幸运的是,它对你的用例大致相同。

Optimised demo

你也可以只使用CSS而不是别的。您可以使用CSS过渡或CSS关键帧动画来处理动画。

CSS-based Demo

答案 1 :(得分:0)

doMove函数

中添加终止条件
function doMove() {
    move.style.left = parseInt(move.style.left) + 2 + 'px';

    if(terminateConditionFullfiled)
        return;

    setTimeout(doMove);
}
相关问题