我正在制作仅通过切换类驱动的幻灯片。所有转换都在CSS中。页面上可能有多个实例。如何在其他人继续时停止点击的那个?
clearInterval()似乎会停止所有实例。
var slideshows = document.querySelectorAll('.slideshow');
function startSlideshow() {
return window.setInterval(function(){
for (var i=0;i<slideshows.length;i++){
var $this = slideshows[i];
var slides = document.querySelectorAll('.current');
for (var i=0;i<slides.length;i++){
var e = slides[i];
if (e == slideshows[i].lastElementChild){
slideshows[i].firstElementChild.classList.add('current');
} else {
e.nextElementSibling.classList.add('current')
};
e.classList.remove('current');
}
}
}, 1000);
}
var id = startSlideshow();
for (var i=0;i<slideshows.length;i++){
slideshows[i].addEventListener('click', function(){
this.classList.toggle('pause');
});
}
.slideshow {height:200px; margin-bottom:1px; width:300px;}
.slide {
background-color:#555;
height:200px;
transition:opacity 0.5s ease-in-out;
opacity:0;
position:absolute;
width:300px;
}
.slide:nth-child(even) {background-color:#d14124;}
.slide.current {opacity:1;}
<div class="slideshow">
<article class="slide current">One</article>
<article class="slide">Two</article>
<article class="slide">Three</article>
<article class="slide">Four</article>
<article class="slide">Five</article>
</div>
<div class="slideshow">
<article class="slide current">1</article>
<article class="slide">2</article>
<article class="slide">3</article>
<article class="slide">4</article>
<article class="slide">5</article>
</div>
答案 0 :(得分:0)
在您当前的实现中,最快的方法是检查是否添加了pause
类,如果是,则跳过动画:if($this.classList.contains('pause'))continue;
但是,因为所有current
项都是使用在document.querySelectorAll('.current')
的每次迭代中slideShows
,你可能想删除内部循环并使用$this.querySelector('.current')
来获取特定幻灯片的当前项目:
var slideshows = document.querySelectorAll('.slideshow');
function startSlideshow() {
return window.setInterval(function(){
for (var i=0;i<slideshows.length;i++){
var $this = slideshows[i];
if($this.classList.contains('pause'))continue;
var e = $this.querySelector('.current');
(e.nextElementSibling || $this.firstElementChild).classList.add('current');
e.classList.remove('current');
}
}, 1000);
}
var id = startSlideshow();
for (var i=0;i<slideshows.length;i++){
slideshows[i].addEventListener('click', function(){
this.classList.toggle('pause');
});
}
另一种选择是让每个幻灯片包含自己的计时器,并启动/停止它。但是,这可能会导致它们在停止/启动后彼此不同步。
顺便说一句,您也可以使用对象,设置dataSet属性或从slideshows
数组中添加/删除div,而不是添加暂停类