防止拖动鼠标时选择文本

Prevent text selection while dragging a mouse

本文关键字:选择 文本 鼠标 拖动      更新时间:2023-09-26

我有以下JavaScript代码执行我的函数,当我按下鼠标左键并在屏幕上拖动它:

function MyFunc(e)
{
   // I copied this part from another SO question
   e.preventDefault();
   e.stopPropagation();
   e.cancelBubble = true;
   e.returnValue = false;
   // This should cancel out all default actions, should it not?

  return false;
}
document.addEventListener('mousemove', MyFunc false);

这应该做的是,当鼠标在屏幕上拖动时(当按下左键时),它会阻止文本(或任何其他元素)被选中。但现实是,它什么也没做。该函数正在执行,我检查了console.log,但它不阻止文本选择。我不知道我哪里做错了。

我现在用的是:

window.getSelection().removeAllRanges();

这是有效的,并强制取消选择,但这是一个非常丑陋的解决方案,我不明白为什么上面的代码不起作用

将此添加到不希望拖动的元素的CSS中。

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;