How can I prevent text/element selection with cursor drag

后端 未结 8 937
刺人心
刺人心 2020-12-02 08:12

I made a paging control and I noticed that while clicking on the buttons it is very easy to accidentally select the individual images and text. Is it possible to prevent thi

相关标签:
8条回答
  • 2020-12-02 08:16

    This is a very old post. It may not answer exactly that situation, but i use CSS for my solution:

    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    
    0 讨论(0)
  • 2020-12-02 08:18

    For dragging, you're capturing the mousedown and mousemove events. (And hopefully touchstart and touchmove events as well, to support touch interfaces.)

    You'll need to call event.preventDefault() in both the down and move events in order to keep the browser from selecting text.

    For example (using jQuery):

    var mouseDown = false;
    $(element).on('mousedown touchstart', function(event) {
      event.preventDefault();
      mouseDown = true;
    });
    $(element).on('mousemove touchmove', function(event) {
      event.preventDefault();
      if(mouseDown) {
        // Do something here.
      }
    });
    $(window.document).on('mouseup touchend', function(event) {
      // Capture this event anywhere in the document, since the mouse may leave our element while mouse is down and then the 'up' event will not fire within the element.
      mouseDown = false;
    });
    
    0 讨论(0)
  • 2020-12-02 08:20

    This can be achieved using CSS in most browsers and the unselectable expando in IE. See my answer here: How to disable text selection highlighting using CSS?

    0 讨论(0)
  • 2020-12-02 08:20

    If you need to block text selection for a certain element using JavaScript, then the simplest method for me was to assign userSelect style like this:

    var myElement = document.createElement('div');
    myElement.style.userSelect = 'none';
    
    0 讨论(0)
  • 2020-12-02 08:23

    simply prevent it by calling blur() function when selected as following :

     <input Value="test" onSelect="blur();">
    
    0 讨论(0)
  • 2020-12-02 08:34

    try this:

    document.onselectstart = function()
    {
        window.getSelection().removeAllRanges();
    };
    
    0 讨论(0)
提交回复
热议问题