繁体   English   中英

使jQuery图像滑块在最后一张图像处停止并添加下一个和上一个按钮

[英]Making a jQuery image slider stop at last image and adding next and prev buttons

我有下面的示例,它遍历每个LI,如果您将鼠标悬停在鼠标悬停时图像会暂停并继续,但是据我所知。

我希望它在到达最后一个LI时停止,并且还想使我添加两个类的链接“ next”和“ prev”,因此如果单击该链接将移至下一个或上一个图像。 当然,如果首先在上一个图像上将类设置为隐藏,而在最后一个图像上将下一个按钮设置为隐藏,那么将无法使用,但是据我所知。

 $( function() { var timer; lis = $(".productImage"); function showNext() { var active = lis.filter(".active").removeClass("active"); var next = active.next(); if (next.length===0) { next = lis.eq(0); } next.addClass("active"); } function showPrev() { var active = lis.filter(".active").removeClass("active"); var prev = active.prev(); if (prev.length===0) { prev = lis.eq(0); } prev.addClass("active"); } function playGallery() { stopGallery(); timer = window.setInterval(showNext, 2500); } function stopGallery() { if (timer) window.clearTimeout(timer); } // move to next image $('.galleryNext').on('click', function(event){ stopGallery(); showNext(); }); // move to previous image $('.galleryPrev').on('click', function(event){ stopGallery(); showPrev(); }); // reset slider timer if thumbnail changed $('.thumbnail-list li a').on('click', function(event){ stopGallery(); playGallery(); }); // pause image slider if mouse is hovering gallery main image $(".featured-image-list") .on("mouseleave", playGallery) .on("mouseenter", stopGallery); playGallery(); }); 
 .productImage { display : none; } .productImage.active { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="featured-image-list"> <li class="productImage active">1</li> <li class="productImage">2</li> <li class="productImage">3</li> <li class="productImage">4</li> <li class="productImage">5</li> </ul> <a class="galleryPrev">prev</a> <a class="galleryNext">next</a> 

修改您的代码几乎没有,我想出了这个:

的jsfiddle

只需将showNext()和showPrev()放在下面的函数中,即可获得下一个和上一个按钮,但需要注意的是,这也会阻止幻灯片自动前进(我在编辑中看到的是您所做的):

function nextImage() {
  stopGallery();
  showNext();
}

function prevImage() {
  stopGallery();
  showPrev();
}

我将由您自己决定解决方案。

您还可以添加以下内容来编辑showNext和showPrev函数:

// add to showNext()
if (next.next().length===0) {
    stopGallery();
    nextBtn.addClass("hidden");
}

// add to showPrev()
if (prev.prev().length===0) {
    prevBtn.addClass("hidden"); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM