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

let posX = 0, posY = 0;
const follower = document.getElementById('follower');
const delay = 20; // 延迟系数
document.addEventListener('mousemove', (e) => {
posX = e.clientX;
posY = e.clientY;
});
function updateFollower() {
const currentX = parseFloat(follower.style.left || 0);
const currentY = parseFloat(follower.style.top || 0);
follower.style.left = `${currentX + (posX - currentX) / delay}px`;
follower.style.top = `${currentY + (posY - currentY) / delay}px`;
requestAnimationFrame(updateFollower);
}
updateFollower();
实现自定义光标
如需替换默认光标为自定义图形:
document.body.style.cursor = 'none';
const customCursor = document.createElement('div');
customCursor.id = 'custom-cursor';
document.body.appendChild(customCursor);
document.addEventListener('mousemove', (e) => {
customCursor.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
});
对应CSS示例:

#custom-cursor {
position: fixed;
width: 32px;
height: 32px;
background: url('cursor.png') no-repeat;
pointer-events: none;
z-index: 9999;
}
高级效果实现
粒子跟随效果
class Particle {
constructor() {
this.x = 0;
this.y = 0;
this.size = Math.random() * 5 + 2;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw(ctx) {
ctx.fillStyle = `hsl(${Math.random() * 360}, 100%, 50%)`;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
document.addEventListener('mousemove', (e) => {
for (let i = 0; i < 5; i++) {
particles.push(new Particle());
particles[particles.length - 1].x = e.clientX;
particles[particles.length - 1].y = e.clientY;
}
});
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw(ctx);
if (particles[i].size <= 0.2) {
particles.splice(i, 1);
i--;
}
}
requestAnimationFrame(animate);
}
animate();
性能优化建议
对于复杂效果,使用Canvas比操作DOM元素性能更好。避免在mousemove事件中直接进行复杂计算,可以使用防抖技术或requestAnimationFrame优化性能。
let mouseX = 0, mouseY = 0;
document.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
function render() {
// 更新逻辑放在这里
requestAnimationFrame(render);
}
render();






