我正在开发一个 jQuery 插件,它隐藏容器内的所有元素,然后使用 fadeIn() 或 jquery 的 animate 函数在设定的时间间隔内显示它们。
到目前为止,我已经成功地将所有元素放入一个数组中,如果我这样做,我可以在警报中打印出 html
$(children).each(function (index, val) {
alert(this);
});
但是,当我尝试再次将元素作为 html 添加到文档中时,我没有运气。
我已经尝试过
$(container).append(this);
和
$(container).appendChild(this);
但还是没有运气。
理想情况下,我需要的是能够再次 fadeIn() 每个元素,并在设定的时间间隔内向每个元素添加 css 类。
(function($) {
$.fn.myPlugin = function (options) {
// Set default options
var defaults = {
rate : '1000',
}
var options = $.extend(defaults, options);
// Hide all elements within parent container
$(this).children().hide();
var container = $(this).selector;
// Store children in loader variable
var loader = $(this).children();
// Put all elements into an array
var children = [];
$(loader).each(function(idx) {
children.push(this.outerHTML);
});
// Iterate over array and fadeIn elements;
$(children).each(function (index, val) {
});
};
})(jQuery);
最佳答案
有点像这样?:http://jsfiddle.net/zKpp2/1/
(function ($) {
$.fn.myPlugin = function (options) {
// Set default options
var defaults = $.extend({
rate: 1000,
}, options);
// Hide all elements within parent container
$(this).children().hide();
var container = $(this).selector;
// Store children in loader variable
var loader = $(this).children(),
length = loader.length;
(function fadeLoop(index){
if (index < length)
loader.eq(index).fadeIn(defaults.rate, function(){
$(this).addClass('foo'); // add class when done animating.
fadeLoop(index + 1);
});
})(0);
};
})(jQuery);
但是,我会推荐一些更灵活的东西:http://jsfiddle.net/zKpp2/3/
(function ($) {
$.fn.myPlugin = function (options) {
// Set default options
var def = $.extend({
rate: 1000,
onStepStart: $.noop,
onStepFinish: $.noop,
onFinish: $.noop
}, options);
// Hide all elements within parent container
$(this).children().hide();
var container = this;
// Store children in loader variable
var loader = $(this).children(),
length = loader.length;
(function fadeLoop(index) {
if (index < length) {
def.onStepStart.apply(
loader.eq(index).fadeIn(def.rate, function () {
def.onStepFinish.apply(this);
fadeLoop(index + 1);
}).get());
} else def.onFinish.apply(container.get());
})(0);
return container;
};
})(jQuery);
您可以像这样使用它来完成您想要的同样的事情(以及许多其他事情):
$("#loader").myPlugin({
rate: 1000,
onStepStart: function(){
$(this).addClass("foo"); // "this" just started fading in
},
onStepFinish: function(){
$(this).removeClass("foo").addClass("bar"); // "this" finished fading in
},
onFinish: function(){
$(this).css("background", "green"); // "this" is the original selector.
}
}).css("background", "red"); // chains properly
编辑 - 该插件的第二个版本不会验证 def.onStepStart
等实际上是函数,因此如果将它们设置为除一个函数。
关于javascript - 使用 jQuery 对数组中的元素进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14403532/