Materialize轮播图:鼠标悬停暂停、离开恢复自动轮播问题求助
Hey there! Let's break down why your current hover pause/resume functionality isn't working as expected and fix it up.
The Root Problem
Your issue boils down to variable scope. In your start() function, you declared var myVar = setInterval(...)—this creates a local myVar inside the function, which is completely separate from the global myVar you defined outside. When stop() tries to run clearInterval(myVar), it’s using the global myVar (which was never assigned the actual timer ID), so the interval never gets cleared properly.
Fixed Code Implementation
Here's the corrected version of your code with key improvements:
$(document).ready(function(){ $('.carousel').carousel(); var myVar; // Global variable to hold the interval ID function start(){ // Avoid creating duplicate intervals if start() is called multiple times if (!myVar) { myVar = setInterval(function(){ $('.carousel').carousel('next'); }, 2500); } } function stop() { clearInterval(myVar); myVar = null; // Reset the variable to allow restarting later } // Attach hover event listeners $('.carousel').mouseenter(stop); $('.carousel').mouseleave(start); // Start the carousel automatically on page load start(); });
Key Fixes Explained:
- Removed
varinsidestart(): Now we assign the interval ID directly to the globalmyVar, sostop()can access the correct ID to clear the interval. - Added a check in
start(): Theif (!myVar)condition prevents creating overlapping intervals if the user hovers in/out quickly, which would make the carousel speed up unexpectedly. - Reset
myVartonullinstop(): This ensures we can safely start a new interval when the mouse leaves the carousel.
Bonus: Use Materialize's Built-in Methods
Did you know Materialize Carousel has native support for automatic rotation and pause/resume? This is often simpler than rolling your own interval:
$(document).ready(function(){ // Initialize carousel with automatic interval $('.carousel').carousel({ interval: 2500 // Auto-advance every 2.5 seconds }); // Use Materialize's native pause/start methods $('.carousel').mouseenter(function(){ $(this).carousel('pause'); }); $('.carousel').mouseleave(function(){ $(this).carousel('start'); }); });
This leverages Materialize's built-in functionality, so you don’t have to manage intervals manually at all!
内容的提问来源于stack exchange,提问作者sandro easy

