gpt4 book ai didi

javascript - 通过计时器启动和停止 Javascript 函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:12 24 4
gpt4 key购买 nike

我的网站上有以下代码....

首先,如何通过单击链接启动动画/功能?

那么,我将如何“卡住”动画中的最后一帧? (可能是定时器?)

谢谢。

HTML 标记:

<div id="anim"></div>

CSS:

#anim {
width: 14px; height: 14px;
background-image: url(http://mail.google.com/mail/im/emotisprites/wink2.png);
background-repeat: no-repeat;
}

Javascript:

var scrollUp = (function () {
var timerId; // stored timer in case you want to use clearInterval later

return function (height, times, element) {
var i = 0; // a simple counter
timerId = setInterval(function () {
if (i > times) // if the last frame is reached, set counter to zero
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up
i++;
}, 100); // every 100 milliseconds
};
})();

// start animation:
scrollUp(14, 42, document.getElementById('anim'))

这是一个 fiddle :http://jsfiddle.net/ctF4t/

最佳答案

你的代码已经准备好了,请阅读第二行:

  var timerId; // stored timer in case you want to use clearInterval later

setInterval 用于定义一次又一次运行的函数一定的间隔。 clearInterval 用于停止此操作。在......的最后您的动画,而不是将帧计数器 i 重置为 0 使用 clearInterval一起停止动画:

        if (i > times) { 
clearInterval(timerId);
}

这是一个带有一些用于调试的额外输出的 fiddle :http://jsfiddle.net/bjelline/zcwYT/

关于javascript - 通过计时器启动和停止 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16382639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com