我处理的dblclick事件在跨度在我的web应用程序。双击的副作用是,它选择了页面上的文本。我怎样才能阻止这种选择的发生呢?
当前回答
或者,在mozilla上:
document.body.onselectstart = function() { return false; } // Or any html object
即,
document.body.onmousedown = function() { return false; } // valid for any html object as well
其他回答
在纯javascript中:
element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);
或者使用jQuery:
jQuery(element).mousedown(function(e){ e.preventDefault(); });
function clearSelection() {
if(document.selection && document.selection.empty) {
document.selection.empty();
} else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
你也可以将这些样式应用到所有非ie浏览器和IE10的span上:
span.no_selection {
user-select: none; /* standard syntax */
-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+ */
}
如果您试图完全阻止通过任何方法以及仅双击选择文本,您可以使用user-select: none css属性。我已经在Chrome 68中进行了测试,但根据https://caniuse.com/#search=user-select,它应该可以在其他当前正常的用户浏览器中工作。
从行为上看,在Chrome 68中,它是由子元素继承的,并且不允许选择元素包含的文本,即使该元素周围的文本已经被选中。
顺风CSS:
<div class="select-none ...">
This text is not selectable
</div>
FWIW,我将user-select: none设置为那些我不希望在双击父元素的任何地方时以某种方式被选中的子元素的父元素。它确实有效!很酷的是contentteditable ="true",文本选择等仍然适用于子元素!
就像:
<div style="user-select: none">
<p>haha</p>
<p>haha</p>
<p>haha</p>
<p>haha</p>
</div>