登录
首页 >  文章 >  前端

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

时间:2024-11-05 15:22:03 389浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《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 中跨区域捕获鼠标移动事件:如何实现? 》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>