js实现瞄
实现鼠标跟随效果
使用JavaScript实现鼠标跟随效果通常涉及监听鼠标移动事件,并更新目标元素的位置。以下是两种常见实现方式:
基础DOM元素跟随
document.addEventListener('mousemove', (e) => {
const follower = document.getElementById('follower');
follower.style.left = `${e.clientX}px`;
follower.style.top = `${e.clientY}px`;
});
带平滑过渡的CSS方案

const follower = document.querySelector('.follower');
let posX = 0, posY = 0;
let mouseX = 0, mouseY = 0;
function animate() {
posX += (mouseX - posX) / 10;
posY += (mouseY - posY) / 10;
follower.style.transform = `translate(${posX}px, ${posY}px)`;
requestAnimationFrame(animate);
}
document.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
animate();
实现自定义光标
替换系统默认光标需要隐藏原生指针并创建自定义元素:
html {
cursor: none;
}
.custom-cursor {
position: fixed;
pointer-events: none;
z-index: 9999;
}
const cursor = document.createElement('div');
cursor.className = 'custom-cursor';
document.body.appendChild(cursor);
document.addEventListener('mousemove', (e) => {
cursor.style.left = `${e.clientX}px`;
cursor.style.top = `${e.clientY}px`;
});
实现元素吸引效果
创建磁吸效果需要计算元素与鼠标的距离:

const magnets = document.querySelectorAll('.magnet');
magnets.forEach(magnet => {
magnet.addEventListener('mousemove', (e) => {
const rect = magnet.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
magnet.style.transform = `translate(${(x - rect.width/2) * 0.2}px, ${(y - rect.height/2) * 0.2}px)`;
});
magnet.addEventListener('mouseout', () => {
magnet.style.transform = 'translate(0, 0)';
});
});
性能优化建议
对于需要高频更新的跟随效果,建议使用CSS的will-change属性:
.follower {
will-change: transform;
}
使用transform属性代替top/left定位能获得更好的性能:
element.style.transform = `translate(${x}px, ${y}px)`;
高级跟随系统
实现带有延迟和缓动的跟随系统:
class Follower {
constructor(target) {
this.target = target;
this.position = { x: 0, y: 0 };
this.speed = 0.1;
this.update();
}
update() {
const dx = mouseX - this.position.x;
const dy = mouseY - this.position.y;
this.position.x += dx * this.speed;
this.position.y += dy * this.speed;
this.target.style.transform = `
translate(${this.position.x}px, ${this.position.y}px)
`;
requestAnimationFrame(() => this.update());
}
}






