我想用简单的分页制作简单的jQuery淡入淡出旋转木马
一切都很好。但是当我点击NEXT
按钮时,轮播会每次都返回第一个项目。
如何解决此问题?
如果小提琴过时,请参阅我的HTML:
<body>
<ul id="carousel">
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide1.jpg" width="960" height="375" alt="image 1" /></li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide2.jpg" width="960" height="375" alt="image 2" /><li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide3.jpg" width="960" height="375" alt="image 3" /></li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide4.jpg" width="960" height="375" alt="image 4" /></li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide5.jpg" width="960" height="375" alt="image 5" /></li>
</ul>
<span class="prev">prev</span>
<span class="next">next</span>
</body>
和脚本:
$(document).ready(function() {
slideShow();
});
function slideShow() {
var showing = $('#carousel .is-showing');
var next = showing.next().length ? showing.next() : showing.parent().children(':first');
showing.fadeOut(800, function() {
next.fadeIn(800).addClass('is-showing');
}).removeClass('is-showing');
setTimeout(slideShow, 5000);
$(".next").click(function() {
showing.fadeOut(800, function() {
next.fadeIn(800).addClass('is-showing');
}).removeClass('is-showing');
})
}
答案 0 :(得分:2)
你需要重写一些代码来解决这个问题。 在功能中拆分重复动作。
新剧本:
$(document).ready(function() {
slideShow();
});
function slideShow() {
var slides = $('#carousel li');
var previousIndex = 0,
currentIndex = 0,
timer;
slides.hide().removeClass('is-showing').eq(currentIndex).show().addClass('is-showing');
function nextSlide() {
previousIndex = currentIndex;
if (currentIndex < slides.length - 1) currentIndex++;
else currentIndex = 0;
switchSlides();
}
function switchSlides() {
slides.eq(previousIndex).removeClass('is-showing').fadeOut(300, function() {
slides.eq(currentIndex).addClass('is-showing').fadeIn(300);
autoRotate();
});
}
function autoRotate() {
clearTimeout(timer);
timer = setTimeout(nextSlide, 5000);
}
autoRotate();
$(".next").click(nextSlide);
}
答案 1 :(得分:1)
因为当你淡出时你删除了“正在显示”的类,所以对于那些800毫秒没有“正在显示”类
showing.fadeOut(800, function() {
next.fadeIn(800).addClass('is-showing');
}).removeClass('is-showing');
所以当它到达这个代码时,没有“当前项目”,所以它按照你的逻辑转到第一个项目
var showing = $('#carousel .is-showing');
var next = showing.next().length ? showing.next() : showing.parent().children(':first');