实现原理分析
鼠标跟随图片效果主要通过以下技术实现:
<img>
标签,设置初始样式document.addEventListener('mousemove')
event.clientX
/event.clientY
style.left
和style.top
基础代码示例
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8">鼠标跟随图片</title> <style> #followImage { position: absolute; width: 100px; height: 100px; pointer-events: none; / 防止遮挡鼠标 / z-index: 999; } </style> </head> <body> <img id="followImage" src="image.png" alt="跟随图片"> <script> const image = document.getElementById('followImage'); document.addEventListener('mousemove', function(e) { // 计算偏移量(示例:鼠标右侧50px,下方50px) let x = e.clientX + 50; let y = e.clientY + 50; // 边界检测(防止超出可视区域) x = Math.min(x, window.innerWidth image.offsetWidth); y = Math.min(y, window.innerHeight image.offsetHeight); // 更新图片位置 image.style.left = x + 'px'; image.style.top = y + 'px'; }); </script> </body> </html>
关键参数说明表
参数名称 | 作用描述 | 取值范围 | 默认建议 |
---|---|---|---|
width/height |
图片尺寸 | 自定义像素值 | 50-150px |
offsetX/Y |
鼠标偏移量 | 正负整数 | ±30-±100 |
pointer-events |
鼠标穿透 | none 或auto |
none |
z-index |
层级控制 | 数值型 | ≥1 |
常见问题与解答
问题1:如何让图片始终保持在鼠标正中心?
解答:调整偏移量计算公式,将坐标设置为鼠标位置减去图片宽高的一半:
let x = e.clientX image.offsetWidth / 2;
let y = e.clientY image.offsetHeight / 2;
问题2:在触摸屏设备上如何实现类似效果?
解答:改用touchmove
事件监听,并获取触摸点坐标:
document.addEventListener('touchmove', function(e) {
let touch = e.touches[0]; // 获取第一个触摸点
let x = touch.clientX image.offsetWidth / 2;
let y = touch.clientY image.offsetHeight / 2;
// 更新位置