开发者

jQuery UI Sortable: Multi-item select

I'd li开发者_开发问答ke 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. 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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜