[英]Animate in elements from array using jQuery
我正在使用一個jQuery插件,該插件將容器中的所有元素都隱藏起來,然后使用fadeIn()或jquery的animate函數在設定的間隔內顯示它們。
到目前為止,我已經設法將所有元素放入數組,如果可以,我可以在警報中打印出html。
$(children).each(function (index, val) {
alert(this);
});
但是,當我嘗試再次將元素作為html添加到文檔中時,我沒有運氣。
我試過了
$(container).append(this);
和
$(container).appendChild(this);
但仍然沒有運氣。
我理想地需要的是能夠再次淡入每個元素,並在設定的間隔內向每個元素添加一個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
等實際上是函數,因此如果將它們設置為函數以外的其他函數,則它將中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.