1. HTML结构搭建
首先需在页面中创建跟随元素,通常使用``标签作为视觉载体:
2. CSS样式定义
为确保元素能定位跟随,需设置定位属性及基础样式: #follower { position: fixed; width: 40px; height: 40px; background: #3498db; border-radius: 50%; pointer-events: none; top: -50px; left: -50px; }- `position: fixed`:脱离文档流,基于视口定位
- `pointer-events: none`:避免遮挡鼠标事件
- 初始`top/left: -50px`:隐藏元素直至鼠标移动
3. JavaScript核心逻辑
通过监听`mousemove`事件获取鼠标坐标,动态更新元素位置: const follower = document.getElementById('follower'); document.addEventListener('mousemove', (e) => { const x = e.clientX; // 鼠标X坐标 const y = e.clientY; // 鼠标Y坐标 follower.style.top = `${y - 20}px`; // 使元素中心对齐鼠标 follower.style.left = `${x - 20}px`; }); 优化:平滑动画与交互体验1. 缓动跟随效果
生硬的位置跳转易显突兀,可通过缓动算法实现平滑过渡: let currentX = 0, currentY = 0; const ease = 0.15; // 缓动系数0~1,值越小越平滑 document.addEventListener('mousemove', (e) => { const targetX = e.clientX - 20; const targetY = e.clientY - 20; currentX += (targetX - currentX) * ease; currentY += (targetY - currentY) * ease; follower.style.transform = `translate(${currentX}px, ${currentY}px)`; });2. 动态样式变化
结合鼠标位置添加互动细节,如颜色、大小随鼠标速度变化: let lastX = 0, lastY = 0; document.addEventListener('mousemove', (e) => { const speedX = Math.abs(e.clientX - lastX); const speedY = Math.abs(e.clientY - lastY); const speed = Math.max(speedX, speedY); follower.style.width = `${40 + speed/2}px`; follower.style.height = `${40 + speed/2}px`; follower.style.backgroundColor = `hsl(${speed * 5}, 70%, 60%)`; lastX = e.clientX; lastY = e.clientY; });3. 性能优化
高频`mousemove`事件易引发性能问题,需通过以下方式优化: - 使用`requestAnimationFrame`替代直接修改样式: function updatePosition() { currentX += (targetX - currentX) * ease; currentY += (targetY - currentY) * ease; follower.style.transform = `translate(${currentX}px, ${currentY}px)`; requestAnimationFrame(updatePosition); } updatePosition();
- 添加节流:限制事件触发频率如每16ms一次 鼠标跟随效果的核心是「坐标监听-状态计算-样式更新」的闭环。通过基础定位实现功能,再结合缓动、动态样式与性能优化,可打造出交互细腻的用户体验。掌握这一逻辑后,可延伸至更复杂的交互场景,如光标拖拽、路径绘制等。
