如何在jQuery动画中连续旋转子级? [英] How to continuously rotate children in a jQuery animation?
问题描述
我有一个班级为'bannergroup'的div,其中包含多个divs'banneritem'.我希望这些项目彼此交替旋转(淡入然后淡出).
I have a div with class 'bannergroup' that contains multiple divs 'banneritem'. I want these items to rotate (fade in then fade out) in place of each other.
我的班级组可以有多个div,每个div应该单独旋转.
I can have several divs with the class bannergroup and each one should rotate separately.
这是HTML:
<div class="bannergroup">
<div class="banneritem">Only visible one at a time</div>
<div class="banneritem">Only visible one at a time</div>
<div class="banneritem">Only visible one at a time</div>
<div class="banneritem">Only visible one at a time</div>
</div>
<div class="bannergroup">
<div class="banneritem">Only visible one at a time</div>
<div class="banneritem">Only visible one at a time</div>
<div class="banneritem">Only visible one at a time</div>
<div class="banneritem">Only visible one at a time</div>
</div>
我的Jquery如下:
My Jquery looks like:
$('.banneritem').css('display', 'none');
$('.bannergroup').children('.banneritem').each(function( i ) {
$(this).fadeIn().delay(4000).fadeOut();
});
问题:每条语句在上一个div完成之前继续运行.我希望它等到前一个孩子走了.另外,我需要它来连续运行.一次之后,它停止.我可以将其放入函数中,但不确定如何再次调用它.
The problem: the each statement continues to run before the previous div completes. I want it to wait until the previous child is gone. Also, I need this to continuously run. After a single time it stops. I can put this into a function, but I am not sure how to know to call it again.
EDIT :并不总是有4个子项.同样,一组的孩子数量可能不同于其他组,但是他们都应同步轮换.可以先完成一个,然后再重新启动.
EDIT: There are not always 4 child items. Also one group may have a different number of children than the others, but they should both rotate in-sync. It is ok if one completes before the other and then just restarts itself.
推荐答案
我已经回答了这个问题多个 次之前.这次,我将尝试将其包装在jQuery插件中. .rotate()
函数会将所需的效果应用于匹配元素的子级,在连续动画中每个子级的淡入/淡出效果.
I have answered this question multiple times before. This time I will try wrapping it in a jQuery plugin. The .rotate()
function will apply the effect you want to the children of the matched elements, a fade in/out effect per children in a continuous animation.
$.fn.rotate = function(){
return this.each(function() {
/* Cache element's children */
var $children = $(this).children();
/* Current element to display */
var position = -1;
/* IIFE */
!function loop() {
/* Get next element's position.
* Restarting from first children after the last one.
*/
position = (position + 1) % $children.length;
/* Fade element */
$children.eq(position).fadeIn(1000).delay(1000).fadeOut(1000, loop);
}();
});
};
用法:
$(function(){
$(".banneritem").hide();
$(".bannergroup").rotate();
});
这篇关于如何在jQuery动画中连续旋转子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!