
如何在 chrome 中实现进度条区域外事件捕捉
问题:
目前,在 Chrome 浏览器中,使用 setCapture() 和 window.captureEvents() 来实现进度条拖动到区域外的事件捕捉已经不再支持。那么,如何实现这一功能呢?
解答:
以下代码展示了如何在 Chrome 浏览器中实现进度条区域外事件捕捉:
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;
// 在这里实现进度条拖动到区域外的处理逻辑
}
function handleMoveEnd(e: MouseEvent) {
window.removeEventListener('mousemove', handleMoving);
window.removeEventListener('mousedown', handleMoveEnd);
startPoint = undefined;
if (document.onselectstart !== originalOnSelectStart) {
document.onselectstart = originalOnSelectStart;
}
}在这个代码中:
- 在 handleMoveStart 函数中,我们记录了鼠标在按下时在进度条上的位置,并禁用文本选择以防止意外的高亮。
- 在 handleMoving 函数中,我们可以实现拖动到进度条区域外的处理逻辑。
- 在 handleMoveEnd 函数中,我们清理了事件监听器和恢复文本选择功能。










