Sortable列表中的适当位置

Sortable列表中的适当位置

本文介绍了强制项目保留在jQuery UI Sortable列表中的适当位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个jQuery可排序列表,但是我需要能够将某些项保留在可排序的固定"位置,并使其他项围绕它们排序.我以为会内置一些方法来实现此目的,可惜情况并非如此.

I've set up a jQuery sortable list but I need to be able to keep some items in the sortable 'fixed' in place and for the other items to sort around them. I thought that there would be built in methods to achieve this, alas this is not the case.

我可以设置列表,但不包含有问题的项目:

I'm able to set up the list and not include the items in question:

<ul id="fruit">
    <li class="fixed">apples</li>
    <li>oranges</li>
    <li>bananas</li>
    <li>pineapples</li>
    <li>grapes</li>
    <li class="fixed">pears</li>
    <li>mango</li>
</ul>

<script type="text/javascript">
    $('#fruit').sortable({items: "li:not('.fixed')"})
</script>

这阻止了我拖放这些项目,但是如果对它们周围的项目进行了排序,它们仍然会移动.可能有一种方法可以使用此方法具有的许多回调,但是我一直无法解决这个问题.

This stops me from drag/dropping these items but they still move if the items around them are sorted. There may be a way to do this using the many callbacks that this method has but I've been unable to work this out.

也许此方法可以很好地添加到UI Sortable选项中?

Maybe this method would be a good addition to the UI Sortable options?

推荐答案

我设法通过稍微修改抖动代码并将其附加到"change"事件而不是"stop"上来做到这一点.我通过查看在拖动项目并设置一些条件时索引的变化来做到这一点.它还适用于多个固定元素. "lockto"变量定义固定元素的位置,并且固定元素最初应位于此位置.您可能会重写它并将其包装在一个函数中,因此不需要为所有固定元素手动设置"lockto"变量.

I managed to do this by modifying jitters code a bit, and attach it to the "change" event rather than the "stop". I did it by looking how the index changes when dragging an item around and set up some conditionals. It also works with multiple fixed elements. The "lockto" variable defines the positon of the fixed element, and the fixed element should be in this position initially. You could probably rewrite this and wrap it in a function so you don't need to manually set the "lockto" variable for all fixed elements.

$("#sortable").sortable({
    "cancel":"li.static",
    "change":function(event,ui) {
        var lockto = 6;
        var thisindex = $(ui.helper).index(fixed);
        var fixed = $("#static-"+lockto);
        var index = $("#sortable li").index(fixed);
        var targetindex = lockto+1;
        if(index !== targetindex) {
            if(index > targetindex ) {
                fixed.prev().insertAfter(fixed); //move it up by one position
            } else if(index==(targetindex-1) && thisindex>targetindex) {
                //don't move it at all
            } else {
                fixed.next().insertBefore(fixed); //move it down by one position
            }
        } else if(index==targetindex && thisindex>targetindex) {
            fixed.prev().insertAfter(fixed); //move it up by one position
        }
    }
});

这篇关于强制项目保留在jQuery UI Sortable列表中的适当位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 02:49