0

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
    }
};

回调的执行不在正确的位置。它似乎在闪烁开始时被触发。任何想法如何在最后闪烁时调用该函数?

小提琴

4

2 回答 2

1

jQuery 动画有一个complete回调参数,因为这些方法是异步的

尝试:

while (times--) {
        this.fadeTo(duration, 0).fadeTo(duration, 1, function(){
            /*last animation is complete*/
           if (typeof callback == 'function') { // make sure the callback is a function
                callback.call(this); // brings the scope to the callback
            } 

        });
    }

API 参考:http ://api.jquery.com/fadeTo/

于 2013-03-30T12:24:42.463 回答
1

我给你写了一个小提琴。您的代码的问题是,循环通过您闪烁的东西快速迭代,并且立即调用了完整的函数。

$(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/

于 2013-03-30T12:30:03.277 回答