What is the best way to prevent highlighting of text when clicking on its containing div in javascript?

前端 未结 4 1654
南方客
南方客 2020-12-05 15:51

I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id\'s of several

相关标签:
4条回答
  • 2020-12-05 16:11

    You could use this CSS to simply hide the selection color (not supported by IE):

    #id::-moz-selection {
      background: transparent;
    }
    
    #id::selection {
      background: transparent;
    }
    
    0 讨论(0)
  • 2020-12-05 16:12

    You could:

    • Give it ("it" being your text) a onclick event
    • First click sets a variable to the current time
    • Second click checks to see if that variable is x time from the current, current time (so a double click over, for example, 500ms, doesn't register as a double click)
    • If it is a double click, do something to the page like adding hidden HTML, doing document.focus(). You'll have to experiment with these as some might cause unwanted scrolling.
    0 讨论(0)
  • 2020-12-05 16:13

    Hope this is what you are looking for.

    <script type="text/javascript">
      function clearSelection() {
        var sel;
        if (document.selection && document.selection.empty) {
          document.selection.empty();
        } else if (window.getSelection) {
          sel = window.getSelection();
          if (sel && sel.removeAllRanges)
            sel.removeAllRanges();
        }
      } 
    </script>
    
    <div ondblclick="clearSelection()">Some text goes here.</div>
    
    0 讨论(0)
  • 2020-12-05 16:14

    In (Mozilla, Firefox, Camino, Safari, Google Chrome) you can use this:

    div.noSelect {
      -moz-user-select: none; /* mozilla browsers */
      -khtml-user-select: none; /* webkit browsers */
    }
    

    For IE there is no CSS option, but you can capture the ondragstart event, and return false;

    Update

    Browser support for this property has expanded since 2008.

    div.noSelect {
      -webkit-user-select: none;  /* Chrome all / Safari all */
      -moz-user-select: none;     /* Firefox all */
      -ms-user-select: none;      /* IE 10+ */
    }
    

    https://css-tricks.com/almanac/properties/u/user-select/

    0 讨论(0)
提交回复
热议问题