[removed] Disable text selection via doubleclick

前端 未结 5 978
走了就别回头了
走了就别回头了 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条回答
  •  Happy的楠姐
    2020-12-03 03:22

    If you really want to disable selection on double-click and not just remove the selection afterwards (looks ugly to me), you need to return false in the second mousedown event (ondblclick won't work because the selection is made onmousedown).

    **If somebody wants no selection at all, the best solution is to use CSS user-select : none; like Maurizio Battaghini proposed.

    // set to true if you want to disable also the triple click event
    // works in Chrome, always disabled in IE11
    var disable_triple_click = true;
    
    // set a global var to save the timestamp of the last mousedown
    var down = new Date().getTime();
    var old_down = down;
    
    jQuery(document).ready(function($)
    {
        $('#demo').on('mousedown', function(e)
        {
            var time = new Date().getTime();
    
            if((time - down) < 500 && 
            (disable_triple_click || (down - old_down) > 500))
            {
                old_down = down;
                down = time;
    
                e.preventDefault(); // just in case
                return false; // mandatory
            }
    
            old_down = down;
            down = time;
        });
    });
    

    Live demo here

    Important notice: I set the sensitivity to 500ms but Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable. - api.jquery.com

    Tested in Chrome and IE11.

提交回复
热议问题