jQuery UI Sortable: Multi-item select

纵然是瞬间 提交于 2019-12-17 18:11:07

问题


I'd like to (via a keyboard operator) select multiple items in an unordered list and drag them to another point in the same list with jQuery Sortable.


回答1:


  1. Select items to sort
  2. Create a custom helper
  3. Hide the selected items until sort is done
  4. Resize the placeholder according to the selection
  5. Manually detach selected items from the current position and attach them to the new position after sort
  6. Show the hidden items (undo step 3) after step5

Here's how I did (Modifying my answer for this question):

$(function() {
  $('ul').on('click', 'li', function() {
    $(this).toggleClass('selected');
  });

  $("ul").sortable({
    revert: true,
    helper: function(e, item) {
      if (!item.hasClass('selected')) item.addClass('selected');
      var elements = $('.selected').not('.ui-sortable-placeholder').clone();
      var helper = $('<ul/>');
      item.siblings('.selected').addClass('hidden');
      return helper.append(elements);
    },
    start: function(e, ui) {
      var elements = ui.item.siblings('.selected.hidden').not('.ui-sortable-placeholder');
      ui.item.data('items', elements);
      var len = ui.helper.children().length;
      var height = ui.item.height() + 5;
      ui.helper.height((len * height))
      ui.placeholder.height((len * height))
    },
    receive: function(e, ui) {
      ui.item.before(ui.item.data('items'));
    },
    stop: function(e, ui) {
      ui.item.siblings('.selected').removeClass('hidden');
      $('.selected').removeClass('selected');
    }
  });

});
* {
  margin: 0;
  padding: 0;
}
#sortable {
  width: 300px;
  padding: 5px;
  margin-right: 100px;
  background: #eee;
  border: 1px solid black;
}
ul li {
  width: 250px;
  margin: 5px;
  padding: 5px;
  font-size: 1.2em;
  cursor: move;
  background-color: white;
  list-style-type: none;
}
.selected {
  background: red !important;
}
.hidden {
  display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<ul id="sortable">
  <li>Item #1</li>
  <li>Item #2</li>
  <li>Item #3</li>
  <li>Item #4</li>
  <li>Item #5</li>
</ul>

(Select multiple items by clicking each of them in the demo)



来源:https://stackoverflow.com/questions/1718851/jquery-ui-sortable-multi-item-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!