2009-10-06 50 views
29

我在JavaScript中實現了項目選擇功能(使用jQuery)。 item是包含一些html的li。
用戶可以點擊一個項目(使其選中),然後按住Shift鍵並單擊另一個項目以選擇其中的所有項目。這基本上可以正常工作,但是shift-click還會選擇(高亮)項目內出現的文本(用於輪班點擊的基本瀏覽器功能)。有什麼辦法可以禁用它嗎?禁用按住'shift'時的文本選擇

回答

35

嘗試組合的JavaScript和CSS以防止選擇首先:

$('li').attr('unselectable', 'on'); // IE 

css(對於瀏覽器不是IE):

li { 
      user-select: none; /* CSS3 (little to no support) */ 
     -ms-user-select: none; /* IE 10+ */ 
     -moz-user-select: none; /* Gecko (Firefox) */ 
    -webkit-user-select: none; /* Webkit (Safari, Chrome) */ 
} 
+0

請注意,unselectable =「on」也必須位於所有子節點上(例如div,p)。即使是複選框小部件也可以按住Shift鍵單擊。 – 2014-04-16 18:39:00

+0

這沒有解決「按下換檔」部分。請參閱@Anthony Mills對此的答案。 – ahlexander 2018-01-16 09:26:37

26

試試這個後移+點擊...

document.getSelection().removeAllRanges(); 

如果這還不夠有效,你可能也必須取消焦點的時候事件......

window.onload = function() { 
    document.onselectstart = function() { 
    return false; 
    } 
} 
+1

+1取消onselectstart。 – 2011-02-03 22:33:59

18

我有這樣的應用程序。竅門是,我想允許選擇,但我也想按住Ctrl並按住Shift鍵點擊選擇項目。

我發現那是什麼每個人,但IE瀏覽器允許您通過取消鼠標按下事件擊敗這一點,並在IE什麼工作最好是暫時焦點的時候禁用:

$("#id").mousedown(function (e) { 
    if (e.ctrlKey || e.shiftKey) { 
     // For non-IE browsers 
     e.preventDefault(); 

     // For IE 
     if ($.browser.msie) { 
      this.onselectstart = function() { return false; }; 
      var me = this; // capture in a closure 
      window.setTimeout(function() { me.onselectstart = null; }, 0); 
     } 
    } 
}); 
+2

這是我正在尋找的祕密。在Chrome上瞬間獲得選擇,並且在Safari上也需要添加'document.getSelection()。removeAllRanges();' – prototype 2014-06-21 02:43:15

5

如果你在你的錶行的複選框(項目),只要您做出選擇,您可以簡單地將焦點設置到該行的複選框。關注複選框應該擺脫瀏覽器選擇。您還可以專注於文本框或其他表單元素。 對於JQuery,

$('tr').bind('click', function(e) { 
    // If shift key was down when the row was clicked 
    if (e.shiftKey) { 
    // Make the row selected 
    $(this).parent().children().slice($(last).index(), $(this).index()+1).addClass('selected').find('input:checkbox').attr('checked', true); 

    // Now focus on the checkbox within the row 
    $('input:checkbox', $(this)).focus(); 
    } 
});