如何用jQuery实现多元素滑块无限循环及悬停暂停功能
Hey there! Let's fix your infinite slider issues step by step. I see a few key problems in your current code that are stopping the infinite loop from working, plus the hover pause isn't implemented yet. Let's break this down:
Key Issues in Your Current Code
- No hover pause for auto-scroll: Your
setIntervalruns non-stop, even when the user hovers over the slider. - Infinite loop logic is broken: The hardcoded
margin-leftreset to 630 doesn't account for dynamic content, and you're not reordering slides properly to create a seamless loop effect. - Animate timing inconsistencies: Some animation calls have incorrect durations (like
000on the Next button) causing jumps, and the interval time doesn't match the animation duration, leading to jank. - State sync issues: Auto-scroll uses
CurrSlideswhile manual clicks useCurrImage, so these two get out of sync and break the slider's state.
Fixes & Implementation
Let's rebuild the auto-scroll and infinite loop logic, plus add hover pause functionality:
Updated HTML (completed your unfinished code)
<div> <div id="MainDiv"> <div id="mainpic"> <img src="img/pic1.jpg" alt="London" id="MainImage" width="100%"/> </div> <div id="child"> <img id="Next" src="img/rightarrow.png" class="NextButton" style="height: 50px;"/> <img id="Previous" src="img/leftarrow.png" class="PreButton" style="height: 50px;"/> </div> </div> <div id="slider"> <ul class="slides"> <li class="slide"> <img src="img/pic1.jpg" alt="London" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic2.jpg" alt="Florence" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic3.jpeg" alt="Amsterdam" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic4.jpg" alt="Venice" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic5.jpg" alt="Prague" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic6.jpg" alt="Krakow" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic7.jpg" alt="Vienna" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic8.jpg" alt="Szczecin" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic9.jpg" alt="Thassos" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic10.jpg" alt="Budapest" width="200" height="120"/> </li> <li class="slide"> <img src="img/pic11.jpg" alt="Pisa" width="200" height="120"/> </li> </ul> </div> </div>
Updated jQuery Code
$(document).ready(function () { // Configuration variables (easy to adjust later) const widthImg = 210; // Width of each slide including spacing const animationSpeed = 800; // Slide animation duration const autoScrollDelay = 3000; // Time between auto-scrolls const BottomLength = 1; // Initialize core variables const $slidesContainer = $('#slider .slides'); const $slides = $('.slides li'); const thumbnail_array = $slides.find('img').map(function () { return $(this).attr("src"); }).get(); const totalSlides = thumbnail_array.length; let currentIndex = 0; let autoScrollInterval; // Set initial state $('#MainImage').attr('src', thumbnail_array[0]); $('#Previous').css("visibility", "hidden"); // Start auto-scroll on load startAutoScroll(); // Hover pause/play functionality $('#slider').hover( function() { clearInterval(autoScrollInterval); // Stop scrolling on hover }, function() { startAutoScroll(); // Resume scrolling when mouse leaves } ); // Thumbnail click handler $('.slides li img').click(function () { const $slide = $(this).parent('.slide'); const imageIndex = $slide.index(); const imageSrc = $(this).attr('src'); const indexDiff = Math.abs(currentIndex - imageIndex); const direction = imageIndex > currentIndex ? '-=' : '+='; $('#MainImage').fadeOut('slow', function () { // Animate to the clicked slide $slidesContainer.animate({ 'margin-left': direction + (widthImg * indexDiff) }, animationSpeed); // Update main image and current state $('#MainImage').attr('src', imageSrc); currentIndex = imageIndex; updateButtonVisibility(); }).fadeIn(3000); }); // Next button click handler $('#Next').click(function () { if (currentIndex >= totalSlides - BottomLength) return; $('#MainImage').fadeOut('slow', function () { currentIndex++; $slidesContainer.animate({ 'margin-left': '-=' + widthImg }, animationSpeed, function() { // Infinite loop: move first slide to end when reaching the right boundary if (currentIndex === totalSlides - BottomLength) { $slidesContainer.append($slides.first()); $slidesContainer.css('margin-left', '-=' + widthImg); } }); $('#MainImage').attr('src', thumbnail_array[currentIndex]); updateButtonVisibility(); }).fadeIn(3000); }); // Previous button click handler $('#Previous').click(function () { if (currentIndex <= 0) return; $('#MainImage').fadeOut('slow', function () { currentIndex--; $slidesContainer.animate({ 'margin-left': '+=' + widthImg }, animationSpeed, function() { // Infinite loop: move last slide to start when reaching the left boundary if (currentIndex === 0) { $slidesContainer.prepend($slides.last()); $slidesContainer.css('margin-left', '+=' + widthImg); } }); $('#MainImage').attr('src', thumbnail_array[currentIndex]); updateButtonVisibility(); }).fadeIn(1000); }); // Thumbnail hover effects $('.slides li img').hover(function () { $(this).css({ 'cursor': 'pointer', 'opacity': '0.5' }); }, function () { $(this).css({ 'cursor': 'default', 'opacity': '1' }); }); // Helper: Update Next/Previous button visibility function updateButtonVisibility() { $('#Previous').css("visibility", currentIndex === 0 ? "hidden" : "visible"); $('#Next').css("visibility", currentIndex >= totalSlides - BottomLength ? "hidden" : "visible"); } // Helper: Start auto-scroll interval function startAutoScroll() { autoScrollInterval = setInterval(function () { $('#Next').click(); // Reuse Next button logic to avoid duplicate code }, autoScrollDelay); } // Set main image height to window height function set_body_height() { $('#mainpic img').height($(window).height()); } $(window).bind('resize', set_body_height); set_body_height(); });
Key Changes Explained
- Centralized Configuration: All adjustable values are at the top, making it easy to tweak slide width, animation speed, or auto-scroll delay later.
- Hover Pause: We bind hover events to the slider container to stop/restart the auto-scroll interval seamlessly.
- Unified State Tracking: A single
currentIndexvariable tracks the active slide, so manual clicks and auto-scroll never get out of sync. - Seamless Infinite Loop: When scrolling to the last slide, we move the first slide to the end (and vice versa for left scrolling) and adjust the margin instantly—this happens after the animation completes, so users don't see a jump.
- Reusable Logic: Auto-scroll triggers the Next button click, eliminating duplicate code for scrolling behavior.
- Cleaned Up Button Logic: The
updateButtonVisibilityhelper handles showing/hiding navigation buttons, reducing redundant code.
内容的提问来源于stack exchange,提问作者Carmen-Maria
相关产品推荐
相关产品推荐

