2

如何更改可排序的开关行为?我的意思是默认情况下1 - 2 - 3 - 4 http://jsfiddle.net/keGuN/ 当我切换位置时4-1它们转换为4 - 1 - 2 - 3. 我只想切换41( 4 - 2 - 3 - 1) 的位置。怎么做?

4

2 回答 2

5

我想我明白你想要做什么。jQuery 的 Sortable 并不是真正设计来满足您的要求。但是,使用 Sortable 公开的事件时,您可以将拖动的项目 (A) 的位置与之前在 A 被放置的位置 (B) 的项目交换位置。我认为这达到了你想要的效果:

jsFiddle 演示

jQuery:

$(function() {
    var oldIndex;

    $("#sortable").sortable({
        start: function(event, ui) {
            oldIndex = ui.item.index();
        },
        stop: function(event, ui) {
            var newIndex = ui.item.index();
            var movingForward = newIndex > oldIndex;            
            var nextIndex = newIndex + (movingForward ? -1 : 1);

            var items = $('#sortable > div');

            // Find the element to move
            var itemToMove = items.get(nextIndex);
            if (itemToMove) {

                // Find the element at the index where we want to move the itemToMove
                var newLocation = $(items.get(oldIndex));

                // Decide if it goes before or after
                if (movingForward) {
                    $(itemToMove).insertBefore(newLocation);
                } else {
                    $(itemToMove).insertAfter(newLocation);
                }
            }
        }
    });

    $("#sortable").disableSelection();
});

唯一值得注意的问题是位置不会在拖动时更新,而只会在项目被放到新位置后更新。

于 2013-09-11T18:01:42.283 回答
5

您可以使用可拖动/可放置来实现交换

$(function() {
$(".swapable").
draggable({ revert: true }).
droppable({
    drop:function(event,ui){
        swapNodes($(this).get(0),$(ui.draggable).get(0));
    }});
});

https://stackoverflow.com/a/698440/2033671

function swapNodes(a, b) {
    var aparent= a.parentNode;
    var asibling= a.nextSibling===b? a : a.nextSibling;
    b.parentNode.insertBefore(a, b);
    aparent.insertBefore(b, asibling);
}

http://jsfiddle.net/keGuN/1/

于 2013-09-11T18:03:23.310 回答