不要拍摄新的动画,直到当前没有结束
Do not shoot new animation until the current does not end
我有一个跳跃动画
$("#bounce").click(function() {
doBounce($(this), 3, '10px', 300);
});
function doBounce(element, times, distance, speed) {
for(i = 0; i < times; i++) {
element
.animate({marginTop: '-='+distance},speed)
.animate({marginTop: '+='+distance},speed);
}
}
但是,当我在元素上单击几次时,各种动画开始,从而形成事件堆栈。我想点击,而当前动画没有结束,不可能启动其他镜头,即使我点击元素。如何做到这一点?
一个解决方案是使用:animated
选择器:
function doBounce(element, times, distance, speed) {
if (element.is(":not(:animated)")) {
for(i = 0; i < times; i++) {
element
.animate({marginTop: '-='+distance},speed)
.animate({marginTop: '+='+distance},speed);
}
}
}
有几种方法,但我建议您使用Javascript scope
设置一个bool值,如果动画完成,返回true。看到这个提琴和点击测试几次,当它是动画。
(function () {
var animate = true;
$("#bounce").click(function () {
// Only fire when true, which it is by default.
if (animate) {
doBounce($(this), 3, '10px', 300);
}
});
function doBounce(element, times, distance, speed) {
// Set to false to prevent new calls.
animate = false;
for (i = 0; i < times; i++) {
element.animate({
marginTop: '-=' + distance
}, speed)
.animate({
marginTop: '+=' + distance
}, speed);
}
// Set the var back to true after animations are finished.
// https://api.jquery.com/promise/
element.promise().done(function () {
animate = true;
alert(animate);
});
}
})();
另一个解决方案是节流功能。节流函数封装另一个(子)函数,并防止每n毫秒调用一次以上的子函数。下面是一个使用lodash库的示例:
var doBounce = _.throttle(function(element, times, distance, speed) {
// here, put your original doBounce code
}, lengthOfAnimation);
现在,无论你调用doBounce(/* some arguments */);
多少次,实际的代码将不会运行超过一次每lengthOfAnimation毫秒。
当然,这只会在每次动画长度相同的情况下起作用。
lodash: https://lodash.com/
节流:https://lodash.com/docs油门
相关文章:
- 在动画结束之前调用函数
- 如何在上一个动画结束后开始动画
- 在动画结束时自动滚动到锚点
- 如何在动画结束后触发动画
- 如何将开始和结束位置应用于jquery视差动画
- 动画结束侦听器无法正常工作
- jQuery - 检测 CSS 动画是否结束
- 如何使动画线性传递?在开始和结束时不会放慢速度
- 动画结束时执行动画
- JavaScript -- Unity 检查动画是否已结束
- 制作旋转动画:缓慢开始和结束,但在中间快速
- 暂时禁用鼠标滚轮,直到动画结束
- 防止回调运行,直到动画结束
- 动画结束在递归函数中不起作用
- jQuery slideDown 函数在动画结束时垂直跳转
- 在窗口大小调整事件开始时暂停 Greensock 动画,在调整大小事件结束时恢复动画
- CSS3动画结束技术
- 等待多个元素的动画结束
- 霓虹动画结束动画事件
- 在结束动画之前避免鼠标检测