如何在不禁用所有文本选择的情况下使用shift禁用文本选择?

所以我知道这听起来像是重复的,但它不是(或者如果它是,我所能找到的所有可接受的答案都不能按我需要的方式工作)。 问题是:

我正在使用jQuery编写HTML5,我需要制作一个允许多选和控制和移位的网格。 我有这个逻辑工作,但每当你按住Shift键点击它选择网格中的文字。 我想阻止这种选择,但是这里和我发现的其他问题之间的关键区别是:我希望在其他所有时间选择文本。

重申:我想禁用文本选择使用shift WITHOUT禁用指定元素的所有文本选择。 有谁知道我怎么做到这一点?

– 编辑 –
以下(在网格的构造函数中)为我解决了这个问题。 正如回答者所说,我宣布了一个不可选择的课程。

this.gridBody = $("#userGrid"); var handleKeydown = function(e) { e = e || window.event; var keyPressed = e.keyCode || e.which; if (keyPressed == keys.shift) { e.data.gridBody.addClass("unselectable"); } }; var handleKeyup = function(e) { e = e || window.event; var keyPressed = e.keyCode || e.which; if (keyPressed == keys.shift) { e.data.gridBody.removeClass("unselectable"); } }; $(document).on('keydown', this, handleKeydown); $(document).on('keyup', this, handleKeyup); 

这将在文档上绑定一个事件,它在按下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 } } } 

希望我帮助过你。

根据评论

 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 } } } 

您可以考虑的另一种解决方案:您可以通过查看Shift键和切换可选择性来阻止文本选择,而只需清除文本选择。

 window.getSelection().removeAllRanges(); 

我觉得这更方便,因为它可以在你的点击处理程序中运行,以“取消”默认行为。 似乎适用于IE 9+和其他现代浏览器。