在jQuery UI Selectable中启用Shift-Multiselect

我想通过保持shift来在jQuery UI Selectable表中启用多选function。

如果在鼠标点击下按住shift,我可能应该这样做

  • 获取最顶层的选定元素
  • 获取单击元素
  • 选择其间的所有元素

但我无法找到如何以干净的方式做到这一点……

目前我在可选择的配置中得到了这个:

start: function(e) { var oTarget = jQuery(e.target); if(!oTarget.is('tr')) oTarget = oTarget.parents('tr'); } 

所以oTarget是被点击的元素(而e.currentTarget是整个表),但现在是什么? 如何找到已经选择的元素的方式可以告诉我点击的元素是否超过所选元素并选择其中的所有内容?

我已经像这样解决了它,添加到可选元素:

 jQuery(table).mousedown(function(e) { //Enable multiselect with shift key if(e.shiftKey) { var oTarget = jQuery(e.target); if(!oTarget.is('.ui-selectee')) oTarget = oTarget.parents('.ui-selectee'); var iNew = jQuery(e.currentTarget).find('.ui-selectee').index(oTarget); var iCurrent = jQuery(e.currentTarget).find('.ui-selectee').index(jQuery(e.currentTarget).find('.ui-selected')); if (iCurrent < iNew) { iHold = iNew; iNew = iCurrent; iCurrent = iHold; } if(iNew != '-1') { jQuery(e.currentTarget).find('.ui-selected').removeClass('ui-selected'); for (i=iNew;i<=iCurrent;i++) { jQuery(e.currentTarget).find('.ui-selectee').eq(i).addClass('ui-selected'); } e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); return false; } } }).selectable(...) 

我为该function编写了简单的插件。 它不依赖于jQuery ui Selectable插件,据我所知,它可以正常工作。

你可以在这里找到插件代码和简单的例子: http : //jsfiddle.net/bMgpc/170/

要写下面的简单描述。

基本用法:

 $('ul').multiSelect(); 

如果按住“Ctrl”或“Command Key”,则可以逐个选择/取消选择元素。

ul – 包含要选择的内部元素的父级。

有多种选择:

  • keepSelection – true | false – 非常重要的标志。 如果设置为true(默认值),则单击已选择的元素时将不会清除选择(因为它适用于多个道具)
  • multiselect – true | false -if false您只能选择一个元素
  • selected – ‘selected’ – 将添加到所选元素的类
  • filter: – ‘> *’ – 我们要选择哪些元素
  • unselectOn – false |’selector’ – 如果设置,则单击set selector selectio将被删除
  • start:false | function – 启动时回调
  • stop:false | function – 停止回调
  • unselecting:false | function – 单击set“unselectOn”选项时的回调

它是一个开发版本的插件,所以要小心使用

你可以不用这样的插件来做到这一点:

 var prev = -1; // here we will store index of previous selection $('tbody').selectable({ selecting: function(e, ui) { // on select var curr = $(ui.selecting.tagName, e.target).index(ui.selecting); // get selecting item index if(e.shiftKey && prev > -1) { // if shift key was pressed and there is previous - select them all $(ui.selecting.tagName, e.target).slice(Math.min(prev, curr), 1 + Math.max(prev, curr)).addClass('ui-selected'); prev = -1; // and reset prev } else { prev = curr; // othervise just save prev } } }); 

这是现场演示: http : //jsfiddle.net/mac2000/DJFaL/1/embedded/result/

环顾四周后,我仍然无法找到解决这个问题的方法,同时仍然使用jQuery UI的Selectable函数,所以我写了一个。 从本质上讲,它可以利用Selectable的选定/未选定回调来管理DOM状态,同时仍然遵循标准的可选API来回应回调。 它支持以下用例:

  • 单击列表中任意位置的其中一个元素(shift +单击,cntl +单击或单击+拖动)
  • 按住Shift并单击列表中的另一个元素
  • 加上两个端点之间的所有元素都将被选中

表的用法:

 $('table').shiftSelectable({filter: 'tr'}); 

几点说明。 (1)它目前只支持兄弟元素。 (2)它将通过配置选项,如表格示例中所示,以及可选方法。 (3)我心脏强调.js所以它被使用,即使为此它并不是必需的。 如果您不想使用这个非常棒的库,请随意更换其简单的检查并进行扩展。 不,我与underscore.js没有任何关系。 🙂

表小提琴的例子

列举小提琴的例子

希望这有助于其他人! 干杯。