Chrome 中跨区域捕获鼠标移动事件:如何实现?

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;  // 根据需要执行操作}function handleMoveEnd(e: MouseEvent) {  window.removeEventListener('mousemove', handleMoving);  window.removeEventListener('mousedown', handleMoveEnd);  startPoint = undefined;  if (document.onselectstart !== originalOnSelectStart) {    document.onselectstart = originalOnSelectStart;  }}

登录后复制

工作原理:

当用户在按钮上按下鼠标时,handleMoveStart() 函数被触发。它阻止默认选择行为,启用鼠标移动事件,并保存鼠标按下时游标的初始位置。

当鼠标移动时,handleMoving() 函数会根据需要执行操作。

当用户释放鼠标时,handleMoveEnd() 函数会移除事件侦听器,清除初始位置,并恢复原始的选择开始事件处理函数。

以上就是Chrome 中跨区域捕获鼠标移动事件:如何实现?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2809155.html

(0)
上一篇 2025年3月8日 22:56:05
下一篇 2025年3月8日 22:56:15

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论