How can I disable text selection using shift without disabling all text selection?

后端 未结 2 2009
遥遥无期
遥遥无期 2021-01-12 00:31

So I know this sounds like a duplicate, but it isn\'t (or if it is, the accepted answer on all the ones I can find doesn\'t work the way I need it to). The issue is this:

相关标签:
2条回答
  • 2021-01-12 00:51

    That will bind on document an event where it disables text selection upon pressing DOWN shift

     document.onkeydown = function(e) {
      var keyPressed = e.keyCode;
      if (keyPressed == 16) { //thats the keycode for shift
    
        $('html').css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none',
           '-webkit-user-select':'none',
           '-ms-user-select':'none',
           'user-select':'none'
        }); //or you could pass these css rules into a class and add that class to html instead
    
        document.onkeyup = function() {
          //here you remove css rules that disable text selection
        }
      }
    }
    

    Hopefully i have helped you.

    Based on comments

    document.onkeydown = function(e) {
      var keyPressed = e.keyCode;
      if (keyPressed == 16) { //thats the keycode for shift
    
        $('html').addClass('unselectable'); //unselectable contains aforementioned css rules
    
        document.onkeyup = function() {
           $('html').removeClass('unselectable'); //and simply remove unselectable class making text selection availabe
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-12 00:51

    Another solution you might consider: instead of preventing text selection by watching for shift keys and toggling selectability, you could just clear the text selection.

    window.getSelection().removeAllRanges();
    

    I find this more convenient because it can be run in your click handler to "cancel" the default behavior. Appears to work in IE 9+ and other modern browsers.

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