
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;
}
}










