【发布时间】:2017-12-15 10:51:15
【问题描述】:
我正在尝试为画廊中的缩略图创建一个简单的“幻灯片放映”。每个画廊都是用 jQuery、HTML 和 CSS 以这种方式构建的:
var imageGalleries = $("img.work-image").parent().parent();
var loopImages = function(){
imageGalleries.each(function(){
var children = $(this).children().children();
var childrenLength = children.length - 1;
var i = 0;
children.each(function(index){
var that = $(this);
setTimeout(function(){
children.addClass("hide");
that.removeClass("hide");
if(childrenLength == index){
setTimeout(function(){
setTimeout(loopImages, 0);
}, 1000);
}
}, 1000 * index);
})
})
};
loopImages();
.hide {
display:none;
}
.work-image {
width:100px;
height:100px;
}
<div class="work-container">
<div class="work-inner" style="height: 248px;">
<img class="work-image hide" src="https://www.nationalgeographic.com/content/dam/animals/thumbs/rights-exempt/mammals/d/domestic-dog_thumb.jpg">
<img class="work-image hide" src="http://cdn1-www.dogtime.com/assets/uploads/gallery/korean-jindo-dog-breed-pictures/puppy-1_680-453.jpg">
<img class="work-image hide" src="http://cdn-www.dailypuppy.com/media/dogs/anonymous/patches_maltipoo16.jpg_w450.jpg">
</div>
</div>
<div class="work-container">
<div class="work-inner" style="height: 248px;">
<img class="work-image hide" src="https://www.petmd.com/sites/default/files/scared-kitten-shutterstock_191443322.jpg">
<img class="work-image hide" src="https://www.petmd.com/sites/default/files/cat-lying-on-side.jpg">
<img class="work-image hide" src="http://fixnation.org/wordpress/wp-content/uploads/2014/03/cats-kittens_00379052.jpg">
<img class="work-image hide" src="http://ichef.bbci.co.uk/wwfeatures/live/624_351/images/live/p0/2c/t5/p02ct5b3.jpg">
<img class="work-image hide" src="http://blog.lifesabundance.com/pics/xbeautiful-whiskery-kitty.jpg.pagespeed.ic.t9JK-YIMfw.jpg">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
如您所见,每个缩略图容器都有 .work-container 类,内部 div 有 .work-inner 类。在.work-inner 中,放置了不同数量的图像(在这种情况下,3 只狗合一,5 只猫合一)。 each 函数以1000ms 延迟循环遍历每个图像,通过添加类.hide 隐藏所有图像,然后删除具有当前索引号的图像的类。
我希望每个容器都遍历它们的所有图像,然后重新启动循环,使其无限循环。现在的问题是,当最短的循环结束时,它会重新启动两者,而不仅仅是已经结束的特定循环,并且只会在“幻灯片”重新启动到早期的位置产生这个故障。
如何让循环只单独循环自己?
【问题讨论】:
-
你能做一个 jsfiddle 并分享一下吗?
-
我创建了一个jsfiddle.net/13jmLvyf
-
我把它做成了代码sn-p!
标签: javascript jquery each