如何使用jQuery实现鼠标移动时依次切换Div内图片源?
Hey there! Awesome to see you expanding your JS skills with interactive effects—this is a fun one to build. Let’s walk through exactly how to create that mouse-driven sequential image swap you’re aiming for, step by step.
Core Concept
The idea is simple: track the mouse’s position relative to your image container, convert that position into a progress value (0 to 1), then map that progress to an index in your array of images. As the mouse moves, we’ll update the image source to match the corresponding index.
Full Code Example
First, let’s lay out the HTML, CSS, and JS you’ll need:
HTML
We’ll use a container to hold our image, which makes it easier to track mouse position relative to the image area:
<div class="image-container"> <img id="sequence-img" src="image-0.jpg" alt="Interactive sequence image"> </div>
CSS
Style the container and image to ensure consistent dimensions and behavior:
.image-container { width: 800px; /* Adjust to your image size */ height: 600px; position: relative; overflow: hidden; cursor: crosshair; /* Optional: matches the example's interactive feel */ } #sequence-img { width: 100%; height: 100%; object-fit: cover; /* Ensures image fills container without distortion */ transition: none; /* Disable default image transition for instant swap */ }
JavaScript
This is where the magic happens. We’ll preload images, track mouse movement, and update the image source dynamically:
// Step 1: Define your sequence of image paths (in order!) const imageSequence = [ 'image-0.jpg', 'image-1.jpg', 'image-2.jpg', // Add all your image files here, ending with your last image 'image-9.jpg' ]; // Step 2: Get DOM elements const container = document.querySelector('.image-container'); const sequenceImg = document.getElementById('sequence-img'); const totalImages = imageSequence.length; // Step 3: Preload images to avoid lag during interaction function preloadImages() { imageSequence.forEach(imageSrc => { const img = new Image(); img.src = imageSrc; }); } // Step 4: Calculate which image to show based on mouse position function getCurrentImageIndex(e) { const containerRect = container.getBoundingClientRect(); // Get mouse position relative to the container (0 to container width) const mouseX = e.clientX - containerRect.left; // Convert mouse position to a percentage (0 = left edge, 1 = right edge) const progress = mouseX / containerRect.width; // Map progress to an image index (0 to totalImages - 1) const index = Math.floor(progress * (totalImages - 1)); // Ensure index stays within valid bounds return Math.max(0, Math.min(index, totalImages - 1)); } // Step 5: Update the image source when the mouse moves function updateImage(e) { const currentIndex = getCurrentImageIndex(e); sequenceImg.src = imageSequence[currentIndex]; } // Optional: Throttle updates for better performance (if you have many images) let isUpdating = false; function throttledUpdate(e) { if (!isUpdating) { requestAnimationFrame(() => { updateImage(e); isUpdating = false; }); isUpdating = true; } } // Step 6: Initialize everything preloadImages(); // Use throttledUpdate instead of updateImage if you need performance tweaks container.addEventListener('mousemove', updateImage); // Optional: Reset to first image when mouse leaves the container container.addEventListener('mouseleave', () => { sequenceImg.src = imageSequence[0]; });
Key Explanations
- Preloading Images: This ensures all images are loaded before the user interacts, so there’s no delay or flickering when swapping sources.
- Mouse Position Mapping: We calculate how far the mouse is across the container (as a percentage) and use that to pick the right image from our sequence. For vertical movement instead of horizontal, just swap
mouseXwithmouseYandcontainerRect.widthwithcontainerRect.heightin thegetCurrentImageIndexfunction. - Performance Throttling: If you’re using 20+ images, the
throttledUpdatefunction reduces the number of image source changes to match your screen’s refresh rate, preventing jank.
Pro Tips
- Image Consistency: Make sure all images in your sequence are the exact same dimensions—this ensures a smooth, glitch-free transition.
- File Size Optimization: Compress your images to reduce load times (tools like TinyPNG work great for this).
- Customization: Adjust the
width/heightin CSS to fit your layout, or modify the progress calculation to trigger the sequence over a different area.
Hope this helps you nail that effect—happy coding!
内容的提问来源于stack exchange,提问作者Ted_M

