chrome 区域外事件捕捉实现
虽然 setCapture() 方法在 Google Chrome 中不受支持,并且 window.captureEvents() 已被废弃,但仍有方法可以实现进度条拖动至区域外后继续触发鼠标移动事件。
以下代码段展示了一种使用 JavaScript 事件监听器和属性的方法:
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; }}
登录后复制
当用户在进度条元素上按下鼠标按钮时,handleMoveStart 函数会触发。它会阻止默认的 onselectstart 事件并捕捉鼠标移动事件,允许用户将进度条拖动到区域外。
handleMoving 函数处理用户鼠标移动事件,执行所需的逻辑(例如更新进度)。
handleMoveEnd 函数在用户释放鼠标按钮时触发,它将删除鼠标移动事件监听器并恢复原始的 onselectstart 事件行为。
以上就是Chrome 区域外事件捕捉:如何在不支持 setCapture() 的情况下实现进度条拖动?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2808951.html