解决 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。
以上就是Chrome 区域外事件捕捉:如何让进度条拖动超出区域后依然响应鼠标移动?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2809058.html