幻灯片工作奇怪



我正在制作用于学习的幻灯片,但它的效果很奇怪。 只有第一和第二霆元素在移动。我无法很好地解释这种现象。 这是我的代码。

timer();
function timer(){
	setInterval(function(){slide()}, 2000);
}
function slide(){
	$('.imgs').animate({left:'-300px'},1000,function(){
		$(this).css({'left':0});
		$(this).append($(this).children('.img').eq(0));
	});
}
ul {padding: 0; margin: 0;}
li {list-style: none;}
#box {width: 300px; height: 200px; margin: 50px auto; position: relative; overflow: hidden;}
.imgs {width: 900px; height: 200px; position: relative;}
.img {width: 300px; height: 200px; float: left; position: relative;}
.img:first-child {background: pink;}
.img:nth-child(2) {background: skyblue;}
.img:nth-child(3) {background: grey;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="box">
<ul class="imgs">
<li class="img"></li>
<li class="img"></li>
<li class="img"></li>
</ul>
</div>

移动元素 -300px,直到达到 li 元素的总数

如果计数器达到li元素的总数,则重置它

到达最后一个元素集 -0px 后

timer();
function timer(){
	setInterval(slide(), 2000);
}
function slide(){
var imageWidth = 300
var totalElm = $(".imgs .img").length 
$('.imgs').width(totalElm*imageWidth)
var counter = 0 
return function(){
var next = counter + 1 
if(next < totalElm){
var left = next * imageWidth
$('.imgs').animate({left:'-'+left+'px'},1000,function(){
counter++
});
}else{
$('.imgs').animate({left:'-0px'},1000,function(){
counter = 0
});
}
}
}
ul {padding: 0; margin: 0;}
li {list-style: none;}
#box {width: 300px; height: 200px; margin: 50px auto; position: relative; overflow: hidden;}
.imgs {width: 900px; height: 200px; position: relative;}
.img {width: 300px; height: 200px; float: left; position: relative;}
.img:first-child {background: pink;}
.img:nth-child(2) {background: skyblue;}
.img:nth-child(3) {background: grey;}
.img:nth-child(4) {background: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box">
<ul class="imgs">
<li class="img"></li>
<li class="img"></li>
<li class="img"></li>
<li class="img"></li>
</ul>
</div>

最新更新