如何在不使用 setCapture() 的情况下实现区域外拖动事件触发?

如何在不使用 setCapture() 的情况下实现区域外拖动事件触发?

chrome 区域外事件捕捉

在 chrome 浏览器中,使用 setcapture() 和 window.captureevents() 来实现区域外事件捕捉已不再可行。那么,如何实现进度条拖动至进度条区域外,仍然触发鼠标移动事件呢?

为此,我们采用以下解决方案:

使用 addeventlistener 监听 mousedown 事件。记录鼠标起始位置。禁用文本选择,防止干扰拖动。监听 mousemove 和 mousedown 事件,在区域外继续触发移动事件。

具体代码如下:

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

登录后复制

以上就是如何在不使用 setCapture() 的情况下实现区域外拖动事件触发?的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

点点赞赏,手留余香

给TA打赏
共0人
还没有人赞赏,快来当第一个赞赏的人吧!
    编程技术

    如何动态修改 Vue+element-ui 中 el-input 组件的样式?

    2025-3-10 14:33:46

    编程技术

    如何解决 margin 塌陷问题?

    2025-3-10 14:33:55

    0 条回复 A文章作者 M管理员
    欢迎您,新朋友,感谢参与互动!
      暂无讨论,说说你的看法吧
    个人中心
    购物车
    优惠劵
    今日签到
    私信列表
    搜索