Chrome 中跨区域捕获鼠标移动事件:如何实现?
时间:2024-11-05 15:22:03 389浏览 收藏
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《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学习网公众号!
相关阅读
更多>
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
392 收藏
-
321 收藏
-
2. CSS 样式使用 ::after 伪元素来在图片上叠加文字:
.im" class="aBlack">CSS图片上叠加文字的实现方法,主要通过使用伪元素(如 ::after)来在图片上方添加内容。以下是详细步骤和示例代码:1. HTML 结构假设你有一个包含图片的容器,结构如下:2. CSS 样式使用 ::after 伪元素来在图片上叠加文字: .im
318
收藏
265
收藏
445
收藏
477
收藏
435
收藏
315
收藏
275
收藏
367
收藏
402
收藏
496
收藏