2

我想在我的自定义 jQuery 插件中添加 after 和 before 回调。我以前从未尝试过回调。所以请帮助我。

这是我的插件代码


(function($){
    $.fn.OneByOne = function( options ){

        var defaults = {
            startDelay:5,           
            duration: 1000,
            nextDelay: 700
        };

        var options = $.extend(defaults, options);
        var delay = options.startDelay;
        return this.each(function(){

            var o = options;
            var obj = $(this);                
            var a = $('a', obj);        

            obj.css({'margin-top':'100px','opacity': '0'});         
            obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration);
            delay += o.nextDelay;


        });


    };
})(jQuery);

在回调之前和之后在哪里调用


我想在before之前调用回调:

    obj.css({'margin-top':'100px','opacity': '0'});         
    obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration);
    delay += o.nextDelay;

并且想after在上面的代码之后调用回调。

我需要什么回调


我想用

http://ricostacruz.com/jquery.transit/

我的回调中的过渡。

还请告诉我在调用插件时如何使用回调。

谢谢。

4

1 回答 1

2
  1. 让用户在回调之前和之后通过。在您的默认值中,指定一个默认回调函数:

    var defaults = {
        startDelay:5,           
        duration: 1000,
        nextDelay: 700 
    };
    
    // Test if user passed valid functions
    options.before = typeof options.before == 'function' ? options.before || function(){};
    options.after = typeof options.after == 'function' ? options.after || function(){};
    

    $ 插件中的选项以散列形式传递,因此用户将它们传递为

    $("…").OneByOne({…, before: function() {}, after: function() {});
    
  2. 在您的插件代码中,您必须挂钩它们以便调用它们(默认的,或任何用户定义的回调):

    // Before is simply called before starting animation
    // Use call or apply on the callback passing any wanted argument.
    before.call(this, obj);
    // After callback is passed directly to animate function and gets called on animation complete.
    obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration, after);
    
  3. “之前”回调的任何参数都将在用户定义的回调之前可用;回调后将使用obj上下文调用,因此在回调后定义的任何用户中,$(this)您的 obj。

于 2013-05-13T12:13:08.140 回答