js实现鼠标滑动
鼠标滑动效果实现方法
基础鼠标跟随效果
通过监听mousemove事件获取鼠标坐标,并更新元素位置:
document.addEventListener('mousemove', (e) => {
const follower = document.getElementById('follower');
follower.style.left = `${e.clientX}px`;
follower.style.top = `${e.clientY}px`;
});
平滑跟随动画
使用CSS过渡或requestAnimationFrame实现平滑移动:

let posX = 0, posY = 0;
const follower = document.getElementById('follower');
function animate() {
const diffX = posX - follower.offsetLeft;
const diffY = posY - follower.offsetTop;
follower.style.left = `${follower.offsetLeft + diffX * 0.1}px`;
follower.style.top = `${follower.offsetTop + diffY * 0.1}px`;
requestAnimationFrame(animate);
}
document.addEventListener('mousemove', (e) => {
posX = e.clientX;
posY = e.clientY;
});
animate();
轨迹记录与回放
存储鼠标坐标并实现轨迹回放:
const points = [];
let isRecording = false;
document.addEventListener('mousemove', (e) => {
if (isRecording) {
points.push({ x: e.clientX, y: e.clientY });
}
});
function replay() {
let index = 0;
const interval = setInterval(() => {
if (index >= points.length) {
clearInterval(interval);
return;
}
follower.style.left = `${points[index].x}px`;
follower.style.top = `${points[index].y}px`;
index++;
}, 16);
}
视觉特效增强
添加拖尾效果和粒子动画:

document.addEventListener('mousemove', (e) => {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = `${e.clientX}px`;
particle.style.top = `${e.clientY}px`;
document.body.appendChild(particle);
setTimeout(() => {
particle.remove();
}, 1000);
});
性能优化建议
避免频繁的DOM操作,使用transform属性代替top/left:
follower.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
考虑使用事件节流减少处理频率:
let lastTime = 0;
document.addEventListener('mousemove', (e) => {
const now = Date.now();
if (now - lastTime > 16) {
updatePosition(e);
lastTime = now;
}
});






