2015-09-28 26 views
1

我有这个以下,其执行我的功能,当我按下鼠标左键,并在屏幕上拖动它的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(); 

这工作和focrefully取消选择,但是这是非常丑陋的解决方案,我不明白为什么上面的代码不起作用。

回答

2

将此添加到您不想拖动的元素的CSS。

-webkit-user-select: none; 
-khtml-user-select: none; 
-moz-user-select: none; 
-ms-user-select: none; 
user-select: none; 
相关问题