[removed] Disable text selection via doubleclick

前端 未结 5 983
走了就别回头了
走了就别回头了 2020-12-03 02:49

When double-clicking on a html page most browsers select the word you double-click on (or the paragraph you triple-click on). Is there a way to get rid of this behavior?

5条回答
  •  爱一瞬间的悲伤
    2020-12-03 03:17

    I fear you can't prevent the selection itself being "native behavior" of the browser, but you can clear the selection right after it's made:

    
    

    Edit: to also prevent selecting whole paragraph by "triple click", here is the required code:

    var _tripleClickTimer = 0;
    var _mouseDown = false;
    
    document.onmousedown = function() {
        _mouseDown = true;
    };
    
    document.onmouseup = function() {
        _mouseDown = false;
    };
    
    document.ondblclick = function DoubleClick(evt) {
        ClearSelection();
        window.clearTimeout(_tripleClickTimer);
    
        //handle triple click selecting whole paragraph
        document.onclick = function() {
            ClearSelection();
        };
    
        _tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
    };
    
    function RemoveDocumentClick() {
        if (!_mouseDown) {
            document.onclick = null; 
            return true;
        }
    
        _tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
        return false;
    }
    
    function ClearSelection() {
        if (window.getSelection)
            window.getSelection().removeAllRanges();
        else if (document.selection)
            document.selection.empty();
    }​
    

    Live test case.

    Should be cross browser, please report any browser where it's not working.

提交回复
热议问题