簡體   English   中英

如何在不禁用所有文本選擇的情況下使用shift禁用文本選擇?

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

所以我知道這聽起來像是重復的,但它不是(或者如果它是,我所能找到的所有可接受的答案都不能按我需要的方式工作)。 問題是:

我正在使用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+和其他現代瀏覽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM