
解决 chrome 区域外事件捕捉
问题:
如何在 Chrome 中实现进度条拖动到进度条区域外时依然触发鼠标移动事件?
答案:
由于 Chrome 中不再支持 setCapture() 和 window.captureEvents(),我们可以使用以下代码实现:
const button = document.querySelector('button');
button?.addEventListener('mousedown', handleMoveStart);
let startPoint: { x: number; y: number } | undefined;
let originalOnSelectStart: Document['onselectstart'] = null;
function handleMoveStart(e: MouseEvent) {
e.stopPropagation();
if (e.ctrlKey || [1, 2].includes(e.button)) return;
window.getSelection()?.removeAllRanges();
e.stopImmediatePropagation();
window.addEventListener('mousemove', handleMoving);
window.addEventListener('mousedown', handleMoveEnd);
originalOnSelectStart = document.onselectstart;
document.onselectstart = () => false;
startPoint = { x: e.x, y: e.y };
}
function handleMoving(e: MouseEvent) {
if (!startPoint) return;
// DO Something
}
function handleMoveEnd(e: MouseEvent) {
window.removeEventListener('mousemove', handleMoving);
window.removeEventListener('mousedown', handleMoveEnd);
startPoint = undefined;
if (document.onselectstart !== originalOnSelectStart) {
document.onselectstart = originalOnSelectStart;
}
}解析:
- 通过 mousedown 事件,捕获鼠标按下的位置(startPoint)。
- 添加 mousemove 事件监听器,在鼠标移动时执行某些操作。
- 禁用页面上的文本选择功能,避免干扰进度条拖动。
- 当鼠标在其他区域释放时,清除监听器并重置 startPoint。










