双击后防止文本select

我正在处理我的Web应用程序中的跨度的dblclick事件。 副作用是双击select页面上的文本。 我怎样才能防止这种select发生?

function clearSelection() { if(document.selection && document.selection.empty) { document.selection.empty(); } else if(window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } 

您也可以将这些样式应用于所有非IE浏览器和IE10的跨度:

 span.no_selection { -webkit-user-select: none; /* webkit (safari, chrome) browsers */ -moz-user-select: none; /* mozilla browsers */ -khtml-user-select: none; /* webkit (konqueror) browsers */ -ms-user-select: none; /* IE10+ */ } 

在纯javascript:

 element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false); 

或者用jQuery:

 jQuery(element).mousedown(function(e){ e.preventDefault(); }); 

一个简单的Javascript函数,使页面元素内的内容不可选:

 function makeUnselectable(elem) { if (typeof(elem) == 'string') elem = document.getElementById(elem); if (elem) { elem.onselectstart = function() { return false; }; elem.style.MozUserSelect = "none"; elem.style.KhtmlUserSelect = "none"; elem.unselectable = "on"; } } 

或者,在Mozilla上:

 document.body.onselectstart = function() { return false; } // Or any html object 

在IE上,

 document.body.onmousedown = function() { return false; } // valid for any html object as well 

要在双击后防止文本select:

你可以使用MouseEvent#detail属性。 对于mousedown或mouseup事件,它是1加上当前点击计数。

 document.addEventListener('mousedown', function (event) { if (event.detail > 1) { event.preventDefault(); } }, false); 

请参阅https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

要防止IE 8 CTRL和SHIFT单击单个元素上的文本select

 var obj = document.createElement("DIV"); obj.onselectstart = function(){ return false; } 

防止在文档上select文本

 window.onload = function(){ document.onselectstart = function(){ return false; } } 

旧的线程,但我想出了一个解决scheme,我认为是更清洁,因为它不禁用每一个对象的绑定,只有防止随机和不必要的文本select页面上。 这很简单,对我来说很好。 这是一个例子。 我想要防止文本select,当我点击类“箭头右”的对象几次:

 $(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});}); 

HTH!

我有同样的问题。 我通过切换到<a>并添加onclick="return false;"来解决它onclick="return false;" (所以点击它不会添加一个新的条目浏览器的历史)。