ctrl,shift 多选表格行

jerry thinkphp 2015年11月19日 收藏
实现类似资源管理器一样的选择方案
按住ctrl加选,按住shift连选,
active是选中后的CSS效果,自行设计或更改
  1. var lastChecked;
  2.     $('#example tbody').on("click","tr", function(event) {
  3.                  
  4.         if(!lastChecked) {
  5.             lastChecked = this;
  6.         }
  7.          
  8.         if(event.shiftKey) {
  9.             var start = $('#example tbody tr').index(this);
  10.             var end = $('#example tbody tr').index(lastChecked);
  11.      
  12.             for(i=Math.min(start,end);i<=Math.max(start,end);i++) {
  13.                 if (!$('#example tbody tr').eq(i).hasClass('active')){
  14.                     $('#example tbody tr').eq(i).addClass("active");
  15.                 }
  16.             }
  17.             
  18.             //清楚浏览器光标选择
  19.             if (window.getSelection) {
  20.                 if (window.getSelection().empty) {  // Chrome
  21.                     window.getSelection().empty();
  22.                 } else if (window.getSelection().removeAllRanges) {  // Firefox
  23.                     window.getSelection().removeAllRanges();
  24.                 }
  25.             } else if (document.selection) {  // IE
  26.                 document.selection.empty();
  27.             }
  28.         } else if ((event.metaKey || event.ctrlKey)){
  29.             $(this).toggleClass('active');
  30.         } else {
  31.             $('#example tbody tr').removeClass('active');
  32.             $(this).toggleClass('active');  
  33.         }
  34.          
  35.         lastChecked = this;
  36.     });