我做了一个分页控件,我注意到点击按钮时很容易意外地选择单个图像和文本。是否有可能阻止这种情况?
澄清选择我的意思是用鼠标突出显示。 (尝试将鼠标从屏幕的一侧拖到另一侧。)
如果您尝试突出显示此网格中的文本/控件,则无法选择该文本/控件。怎么做的? Link
答案 0 :(得分:93)
拖动并选择在鼠标按下事件上初始化并在随后的鼠标移动时更新。处理事件以开始拖动或跟随鼠标时,取消事件的冒泡并覆盖默认的浏览器返回:
在您开始拖动mousedown并移动处理程序时会发生类似这样的事情 -
e=e || window.event; pauseEvent(e);
function pauseEvent(e){
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
}
答案 1 :(得分:39)
对于拖动,您正在捕获mousedown
和mousemove
事件。 (并且希望touchstart
和touchmove
事件也支持触摸界面。)
您需要在event.preventDefault()
和down
事件中致电move
,以防止浏览器选择文字。
例如(使用jQuery):
var mouseDown = false;
$(element).on('mousedown touchstart', function(event) {
event.preventDefault();
mouseDown = true;
});
$(element).on('mousemove touchmove', function(event) {
event.preventDefault();
if(mouseDown) {
// Do something here.
}
});
$(window.document).on('mouseup touchend', function(event) {
// Capture this event anywhere in the document, since the mouse may leave our element while mouse is down and then the 'up' event will not fire within the element.
mouseDown = false;
});
答案 2 :(得分:17)
我想发表评论,但我没有足够的声誉。 使用@kennebec建议的功能在我的javascript拖动库中解决了我的问题。 它完美无瑕。
function pauseEvent(e){
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
}
我在我的mousedown和mousemove自定义函数中调用它,在我能识别出我点击右边元素后立即调用它。如果我只是在函数的顶部调用它,我只是杀死文档上的任何单击。 我的函数在document.body上注册为事件。
答案 3 :(得分:7)
这可以通过大多数浏览器中的CSS和IE中的unselectable
expando来实现。请在此处查看我的回答:How to disable text selection highlighting using CSS?
答案 4 :(得分:6)
试试这个:
document.onselectstart = function()
{
window.getSelection().removeAllRanges();
};
答案 5 :(得分:5)
这是一个非常古老的帖子。它可能无法完全回答这种情况,但是我将CSS用于解决方案:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
答案 6 :(得分:0)
如果你需要使用JavaScript阻止某个元素的文本选择,那么对我来说最简单的方法就是分配userSelect样式:
var myElement = document.createElement('div');
myElement.style.userSelect = 'none';