js鼠标事件实现动效
鼠标事件基础
鼠标事件是JavaScript中实现交互效果的核心,常用事件包括click、mouseover、mouseout、mousemove、mousedown、mouseup等。通过监听这些事件,可以触发CSS或JavaScript动画。
监听鼠标事件
通过addEventListener绑定事件,例如实现元素悬停放大效果:
const box = document.querySelector('.box');
box.addEventListener('mouseover', () => {
box.style.transform = 'scale(1.2)';
box.style.transition = 'transform 0.3s ease';
});
box.addEventListener('mouseout', () => {
box.style.transform = 'scale(1)';
});
结合CSS过渡
通过CSS定义动画属性,JavaScript仅控制状态变化:
.box {
transition: all 0.3s ease;
}
box.addEventListener('mouseenter', () => {
box.classList.add('hover-effect');
});
box.addEventListener('mouseleave', () => {
box.classList.remove('hover-effect');
});
拖拽效果实现
利用mousedown、mousemove和mouseup实现拖拽:
let isDragging = false;
box.addEventListener('mousedown', (e) => {
isDragging = true;
const offsetX = e.clientX - box.getBoundingClientRect().left;
const offsetY = e.clientY - box.getBoundingClientRect().top;
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
box.style.left = `${e.clientX - offsetX}px`;
box.style.top = `${e.clientY - offsetY}px`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
});
鼠标跟随特效
通过mousemove事件获取光标位置,动态调整元素样式:
document.addEventListener('mousemove', (e) => {
const x = e.clientX;
const y = e.clientY;
const follower = document.querySelector('.follower');
follower.style.left = `${x + 10}px`;
follower.style.top = `${y + 10}px`;
});
高级动画库结合
使用GSAP或Anime.js增强效果,例如实现弹性跟随:
gsap.to('.follower', {
x: mouseX,
y: mouseY,
duration: 0.5,
ease: 'elastic.out(1, 0.3)'
});
性能优化
减少mousemove事件的计算负担,使用requestAnimationFrame或节流函数:

function throttle(callback, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
callback(...args);
lastCall = now;
}
};
}
document.addEventListener('mousemove', throttle(updatePosition, 16));






