gpt4 book ai didi

javascript - 调用函数之前等待动画完成

转载 作者:行者123 更新时间:2023-12-02 18:52:04 25 4
gpt4 key购买 nike

JS:

$.fn.blink = function(times, duration) {
times = times || 2;

while (times--) {
this.fadeTo(duration, 0).fadeTo(duration, 1);
}
};

这会使文本闪烁。最后眨眼我想执行一个函数,所以我将其更改如下:

$.fn.blink = function(times, duration, callback) {
times = times || 2;

while (times--) {
this.fadeTo(duration, 0).fadeTo(duration, 1);
}

if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
};

回调的执行位置不对。当眨眼开始时它似乎被触发。有什么想法如何在最后闪烁时调用该函数吗?

FIDDLE

最佳答案

我给你写了一个 fiddle 。您的代码的问题是,循环快速迭代您的闪烁内容,并且立即调用完整的函数。

$(document).ready(function () {
$('.blink').blink(5, 500, shout);
});

function shout() {
alert('finished blinking');
}

$.fn.blinkOnce = function (duration, callback) {
this.fadeTo(duration, 0).fadeTo(duration, 1, function () {
if (typeof callback == 'function') callback.call(this);
});
};

$.fn.blink = function (times, duration, callback) {
var toBlink = this;
var blinkComplete = function () {
times--;
if (times == 0) callback.call(this);
else toBlink.blinkOnce(duration, blinkComplete);
}

toBlink.blinkOnce(duration, blinkComplete);
return true;
};

http://jsfiddle.net/xgeLu/

关于javascript - 调用函数之前等待动画完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15718397/

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