我想在我的自定义 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/
回调中的转换。
请告诉我如何在调用插件时使用回调。
谢谢。
最佳答案
让用户在回调之前和之后传递。 在默认值中,指定默认回调函数:
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() {});
在您的插件代码中,您必须 Hook 它们以便调用它们(默认的,或任何用户定义的回调):
// 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);
“before”回调的任何参数都可以在用户定义的回调之前使用; after 回调将使用 obj 上下文调用,因此在回调后定义的任何用户内,$(this) 是你的 obj。
关于jQuery - 在插件中添加回调前后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16520922/