Vue组件问题:实现鼠标移入Div时显示跟随鼠标的图片
Fixing Vue Mouse-Follow Image Component
Hey Shawn, let's get your mouse-follow image working properly! I'll walk through the key adjustments needed to make the image show on hover and track your mouse movement smoothly.
1. Complete the Template Structure
First, you need to add the image element to your template and wire up the hover events to toggle visibility. Here's the full template:
<div id="app"> <div class="container" @mouseover="showImage = true" @mouseout="showImage = false" @mousemove="onMouseMove" > Hover over this container to see the image! </div> <img v-show="showImage" :style="{ left: `${page.left}px`, top: `${page.top}px` }" src="https://picsum.photos/100/100" class="follow-image" > </div>
@mouseoverand@mouseouthandle showing/hiding the image when the user enters/exits the container.v-showconditionally renders the image based on theshowImageflag.:styledynamically binds the image's position to thepagecoordinates from your data.
2. Add Critical CSS for Positioning
Without proper CSS, the image won't position correctly. Add these styles:
.container { height: 400px; width: 400px; border: 1px solid #ccc; background: #f5f5f5; } .follow-image { position: fixed; /* Positions relative to the viewport */ /* Use position: absolute; instead if you want it relative to the container (add position: relative; to .container) */ pointer-events: none; /* Prevents the image from blocking mouse events */ width: 100px; height: 100px; }
position: fixedlets the image follow the mouse across the entire viewport. If you want it constrained to the container, switch toposition: absoluteand addposition: relativeto the.container.pointer-events: noneis important—it stops the image from triggeringmouseoutwhen the mouse moves over it, which would hide the image unexpectedly.
3. Tweak the Vue Script (Minor Cleanup)
Your existing script is almost there, but we can make a small adjustment to ensure smooth updates (though your original code works fine):
new Vue({ el: '#app', data: { showImage: false, page: { left: 0, top: 0 }, }, methods: { onMouseMove(e) { // Update coordinates with mouse position this.page.left = e.pageX; this.page.top = e.pageY; } } })
The e.pageX and e.pageY values give the correct mouse position relative to the document, which works perfectly with position: fixed.
Why This Works
- The hover events toggle the image visibility reliably.
- Dynamic style binding ensures the image's position updates in real-time as the mouse moves.
- Proper CSS positioning removes layout constraints that would prevent the image from following the mouse.
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

