js实现鼠标移动
监听鼠标移动事件
使用 mousemove 事件监听鼠标移动,通过回调函数获取鼠标的坐标信息(clientX 和 clientY)。
document.addEventListener('mousemove', (event) => {
const x = event.clientX;
const y = event.clientY;
console.log(`鼠标位置:X=${x}, Y=${y}`);
});
实时显示鼠标坐标
在页面上动态更新鼠标坐标的显示,例如通过一个 <div> 元素。

const coordDisplay = document.createElement('div');
coordDisplay.style.position = 'fixed';
coordDisplay.style.bottom = '10px';
coordDisplay.style.right = '10px';
document.body.appendChild(coordDisplay);
document.addEventListener('mousemove', (event) => {
coordDisplay.textContent = `X: ${event.clientX}, Y: ${event.clientY}`;
});
跟随鼠标移动的元素
创建一个元素(如圆形或图标),使其跟随鼠标移动。
const follower = document.createElement('div');
follower.style.width = '20px';
follower.style.height = '20px';
follower.style.backgroundColor = 'red';
follower.style.borderRadius = '50%';
follower.style.position = 'fixed';
follower.style.pointerEvents = 'none'; // 防止遮挡点击事件
document.body.appendChild(follower);
document.addEventListener('mousemove', (event) => {
follower.style.left = `${event.clientX - 10}px`;
follower.style.top = `${event.clientY - 10}px`;
});
限制移动范围
通过逻辑判断限制鼠标移动的响应范围,例如仅在特定区域内触发。

const boundary = { minX: 100, maxX: 500, minY: 100, maxY: 500 };
document.addEventListener('mousemove', (event) => {
const x = Math.max(boundary.minX, Math.min(event.clientX, boundary.maxX));
const y = Math.max(boundary.minY, Math.min(event.clientY, boundary.maxY));
console.log(`限制后坐标:X=${x}, Y=${y}`);
});
性能优化
使用防抖(debounce)或节流(throttle)减少事件触发频率,避免高频更新导致的性能问题。
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((event) => {
console.log(`节流坐标:X=${event.clientX}, Y=${event.clientY}`);
}, 100));
兼容性处理
检查浏览器是否支持 mousemove 事件,并提供备用方案(如触摸事件)。
if ('onmousemove' in window) {
document.addEventListener('mousemove', handleMove);
} else {
console.warn('mousemove 事件不支持');
}






