jQuery自动滚动鼠标悬停暂停功能实现求助
Solution for Auto-Scroll with Hover Pause
Hey there! I see you're working on an auto-scrolling component and want to add a pause-on-hover feature. Let's tweak your existing code to make that happen. Here's how to do it step by step:
First, let's recap and complete your existing scroll setup, then integrate the hover pause logic:
/* Scroll view setup */ $('.scroll').wrap('<div class="scroll-group"></div>'); $('.scroll').css({ 'overflow': 'hidden', height: 'auto' }); $('.scroll-group').append($('.scroll').clone()); $('.scroll-group').wrap('<div class="scroll-wrap"></div>'); $('.scroll-wrap').css({ 'overflow': 'hidden' }); /* Auto-scroll with hover pause logic */ // Store the interval reference so we can clear it later let scrollInterval; const scrollWrap = $('.scroll-wrap'); const scrollGroup = $('.scroll-group'); const scrollHeight = $('.scroll').eq(0).outerHeight(); // Function to handle the auto-scroll animation function startAutoScroll() { scrollInterval = setInterval(() => { scrollGroup.animate({ top: `-=${scrollHeight}` }, 1000, 'linear', () => { // Reset position to create infinite scroll effect if (parseInt(scrollGroup.css('top')) <= -scrollHeight) { scrollGroup.css('top', 0); } }); }, 1000); // Adjust interval duration as needed } // Start the scroll initially startAutoScroll(); // Add hover event listeners to pause/resume scrollWrap.hover( // On mouse enter: pause the scroll function() { clearInterval(scrollInterval); // Also pause any ongoing animation to avoid jank scrollGroup.stop(); }, // On mouse leave: resume the scroll function() { startAutoScroll(); } );
Key Changes Explained:
- Timer Reference: We added
let scrollIntervalto keep track of the auto-scroll timer, so we can stop it cleanly when the user hovers. - Reusable Scroll Function:
startAutoScroll()wraps up the scrolling logic, making it easy to restart the scroll after the hover ends. - Hover Event Handlers:
- When the mouse enters the scroll container, we clear the interval and stop any ongoing animation with
scrollGroup.stop()to prevent choppy behavior. - When the mouse leaves, we call
startAutoScroll()again to pick up the scroll where it left off.
- When the mouse enters the scroll container, we clear the interval and stop any ongoing animation with
- Infinite Scroll Reset: The animation callback resets the scroll group's position once it's scrolled the full height of the content, creating a seamless loop.
You can adjust the 1000 values (animation duration and interval delay) to make the scroll faster or slower based on your needs.
内容的提问来源于stack exchange,提问作者Eshan Rajapakshe
相关产品推荐
相关产品推荐

