【问题标题】:change switch position behavior改变开关位置行为
【发布时间】:2013-09-11 17:28:08
【问题描述】:

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

【问题讨论】:

  • 当我想切换两个元素的位置时 - 其他元素也会改变它们的位置。 1 2 3 4 -> 想要切换4&1 -> 但新订单是4 1 2 3。我只想更改 41 的位置,所以结果应该是 - 4 2 3 1

标签: jquery jquery-ui-sortable


【解决方案1】:

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

jsFiddle demo

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();
});

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

【讨论】:

    【解决方案2】:

    您可以通过可拖动/可放置来实现交换

    $(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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多