重新排序可排序的可拖动Jquery ui列表

时间:2015-02-12 13:22:39

标签: jquery jquery-ui

我有一个可排序,可拖动的Jquery UI列表

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

$( "#list" )
  .sortable({ handle: ".handle" })
  .selectable()
    .find( "li" )
      .addClass( "ui-corner-all" )
      .prepend( "<div class='handle'><span class='ui-icon ui-icon-carat-2-n-s'></span></div>" );

You can see it working here JSFiddle

我能解决的问题是,如何自动重新排序列表。

我想要点击任何元素 - 不移动 - 立即自动跳转到列表顶部。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

以下代码执行类似的操作:

来源:Move list item to top of unordered list using jQuery

JSFiddle:http://jsfiddle.net/yf5fz7xc/1/

 $(document).ready(function() {
    $('li').click(function() {
      // the clicked LI
      var clicked = $(this);

      // all the LIs above the clicked one
      var previousAll = clicked.prevAll();

      // only proceed if it's not already on top (no previous siblings)
      if(previousAll.length > 0) {
        // top LI
        var top = $(previousAll[previousAll.length - 1]);

        // immediately previous LI
        var previous = $(previousAll[0]);

        // how far up do we need to move the clicked LI?
        var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');

        // how far down do we need to move the previous siblings?
        var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());

        // let's move stuff
        clicked.css('position', 'relative');
        previousAll.css('position', 'relative');
        clicked.animate({'top': -moveUp});
        previousAll.animate({'top': moveDown}, {complete: function() {
          // rearrange the DOM and restore positioning when we're done moving
          clicked.parent().prepend(clicked);
          clicked.css({'position': 'static', 'top': 0});
          previousAll.css({'position': 'static', 'top': 0}); 
        }});
      }
    });
  });