js实现mousemove
监听鼠标移动事件
在JavaScript中,可以通过addEventListener方法监听mousemove事件。以下是一个基本实现:
document.addEventListener('mousemove', function(event) {
console.log('鼠标位置:', event.clientX, event.clientY);
});
获取鼠标坐标
mousemove事件对象包含鼠标的坐标信息:
clientX和clientY:相对于浏览器窗口的坐标pageX和pageY:相对于整个文档的坐标screenX和screenY:相对于屏幕的坐标
document.addEventListener('mousemove', function(e) {
console.log('窗口坐标:', e.clientX, e.clientY);
console.log('文档坐标:', e.pageX, e.pageY);
console.log('屏幕坐标:', e.screenX, e.screenY);
});
限制事件触发频率
对于性能敏感的场合,可以使用节流(throttle)技术减少事件触发频率:
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
document.addEventListener('mousemove', throttle(function(e) {
console.log('节流后的鼠标位置:', e.clientX, e.clientY);
}, 100));
跟踪鼠标移动轨迹
记录鼠标移动轨迹并绘制:
const points = [];
document.addEventListener('mousemove', function(e) {
points.push({x: e.clientX, y: e.clientY});
if (points.length > 100) points.shift();
// 绘制轨迹
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
points.forEach((p, i) => {
if (i === 0) ctx.moveTo(p.x, p.y);
else ctx.lineTo(p.x, p.y);
});
ctx.stroke();
});
元素跟随鼠标
实现元素跟随鼠标移动的效果:
const follower = document.getElementById('follower');
document.addEventListener('mousemove', function(e) {
follower.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
});
性能优化建议
对于复杂的鼠标移动交互,考虑以下优化:

- 使用
requestAnimationFrame进行动画更新 - 减少DOM操作,尽量使用CSS变换
- 必要时使用事件委托
- 移除不需要的监听器避免内存泄漏






