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

后端 未结 2 2008
遥遥无期
遥遥无期 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
        }
      }
    }
    

提交回复
热议问题