简体   繁体   English

如何停止动画

[英]How to stop animation

I am rather new to programming and have just begun learning Javascript. 我是编程新手,刚开始学习Javascript。 I creating a personal portfolio in which I want an image of myself to slide horizontally from one end of the screen the other end. 我创建了一个个人投资组合,我希望自己的图像从屏幕的另一端水平滑动。 I have the code that gets it to slide right horizontally, but I do no know how to stop it. 我有使它水平滑动的代码,但是我不知道如何停止它。

My code looks like this at the moment: 目前,我的代码如下所示:

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;

I think I am supposed to write an if statement and call on the clearTimeout function to stop the animation, but I cant figure out the code. 我想我应该编写一条if语句并调用clearTimeout函数来停止动画,但是我无法弄清楚代码。 Any assistance would be great. 任何帮助都会很棒。

The key is that you're calling doMove() recursively, using setTimeout() to displace the element at a framerate that is perceptible to the human eye. 关键是您要递归调用doMove() ,使用setTimeout()以人眼可以感知的帧速率替换元素。 To stop a recursive function, introduce a condition to terminate it, like so: 要停止递归函数,请引入一个条件来终止它,如下所示:

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 演示版


Consider using CSS transforms instead of modifying left / right properties, as transforms are better optimised and will yield a better frame rate. 考虑使用CSS变换而不是修改left / right属性,因为可以对变换进行更好的优化,并且可以产生更好的帧速率。

It is also recommended to use requestAnimationFrame instead of setTimeout . 还建议使用requestAnimationFrame代替setTimeout Fortunately, it works in much the same way for your use case. 幸运的是,对于您的用例,它的工作方式几乎相同。

Optimised demo 优化演示


You could also just use CSS and nothing else. 您也可以只使用CSS,而不能使用其他任何东西。 You could handle the animation using CSS transitions or CSS keyframe animation. 您可以使用CSS过渡或CSS关键帧动画来处理动画。

CSS-based Demo 基于CSS的演示

Add terminate condition in the doMove function doMove函数中添加终止条件

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

    if(terminateConditionFullfiled)
        return;

    setTimeout(doMove);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM