[英]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>
修改您的代碼幾乎沒有,我想出了這個:
只需將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.