如何停止动画

How to stop animation

提问人:Mwewol 提问时间:10/31/2016 最后编辑:Mwewol 更新时间:10/31/2016 访问量:9905

问:

我是编程的新手,刚刚开始学习 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 函数来停止动画,但我无法弄清楚代码。任何帮助都会很棒。

JavaScript 动画

评论


答:

0赞 Niyoko 10/31/2016 #1

在函数中添加终止条件doMove

function doMove() {
    move.style.left = parseInt(move.style.left) + 2 + 'px';

    if(terminateConditionFullfiled)
        return;

    setTimeout(doMove);
}
1赞 AM Douglas 10/31/2016 #2

关键是你是递归调用的,用于以人眼可感知的帧速率位移元素。要停止递归函数,请引入一个条件来终止它,如下所示: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;

演示


考虑使用 CSS 转换而不是修改 / 属性,因为转换可以更好地优化,并且会产生更好的帧速率。leftright

还建议使用代替 .幸运的是,它的工作方式与您的用例大致相同。requestAnimationFramesetTimeout

优化演示


您也可以只使用 CSS,仅此而已。您可以使用 CSS 过渡或 CSS 关键帧动画来处理动画。

基于 CSS 的演示