我正在我的网络应用程序中处理跨度上的 dblclick 事件。一个副作用是双击会选择页面上的文本。我怎样才能防止这种选择发生?
双击后阻止文本选择
IT技术
javascript
selection-object
                    2021-01-30 00:41:01
                
                    
                
            
        6个回答
            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+ */
}
在普通的javascript中:
element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);
或者使用 jQuery:
jQuery(element).mousedown(function(e){ e.preventDefault(); });
仅在双击后防止文本选择:
你可以使用MouseEvent#detail财产。对于 mousedown 或 mouseup 事件,它是 1 加上当前的点击次数。
document.addEventListener('mousedown', function (event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);
见https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail
FWIW,我设置user-select: none的父元素的子元素的,我不希望以某种方式选择的父元素上双击的任何地方。它有效!很酷的是contenteditable="true",文本选择等仍然适用于子元素!
所以像:
<div style="user-select: none">
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
</div>
一个简单的 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";
  }
}
其它你可能感兴趣的问题