Prevent text selection after double click

2022-08-29 23:44:37

I'm handling the dblclick event on a span in my web app. A side-effect is that the double click selects text on the page. How can I prevent this selection from happening?


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

You can also apply these styles to the span for all non-IE browsers and IE10:

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+ */
}

答案 2

To prevent text selection ONLY after a double click:

You could use property. For or events, it is 1 plus the current click count.MouseEvent#detailmousedownmouseup

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);
Some dummy text

See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail