【问题标题】:jQuery UI sortable: how to leave css values of changed items untouched?jQuery UI 可排序:如何保持更改项目的 css 值不变?
【发布时间】:2014-12-26 11:00:25
【问题描述】:

我有一个按相反顺序设置的 z-indexes 列表:

<ul>
    <li style="z-index: 3;">First item</li>
    <li style="z-index: 2;">Second item</li>
    <li style="z-index: 1;">Third item</li>
</ul>

使用 jQuery UI 可排序,我希望在对项目进行排序时元素的 z-indexes 不改变时达到效果。比如说,我想按以下顺序对所有表示的项目进行排序:第二、第三、第一。但保持 z 索引不变!

谢谢。

这是我到目前为止使用 JS 所取得的成就(我是新手):

$('#widget-2').sortable({
        start: function(event, ui) {
            ui.item.data('originIndex', ui.item.css('z-index'));
        },
        change: function(event, ui) {
            ui.item.data('placeholderIndex', ui.placeholder.css('z-index'));

            var originIndex = ui.item.data('originIndex');
            var placeholderIndex = ui.item.data('placeholderIndex');

            ui.placeholder.css('z-index', originIndex);
            ui.item.css('z-index', placeholderIndex);
        }
    });

【问题讨论】:

标签: javascript jquery html css jquery-ui


【解决方案1】:

由于您已经在页面上使用了 JavaScript,我建议您使用这个小 jQuery 插件计算并在文档准备好时分配 z-index

$.fn.reverseZIndex = function () {
    // get the children of the list.
    var $children = this.children(),
        length = $children.length;

    $children.each(function (index) {
        // assign z-index, high values to low.
        this.style.zIndex = length - index;
    });

    return this;
};

$(document).ready(function () {
    var $widget2 = $('#widget-2');

    // calculate reversed z-index.
    $widget2.reverseZIndex();

    // initialize sortable.
    $widget2.sortable(...);
});

然后您可以在任何给定列表上使用此插件,&lt;ul&gt;&lt;ol&gt;(甚至是父级 &lt;div&gt;),因此子级将有 z-index 以相反的顺序。

change 上的 jQuery 可排序中执行相同操作,以更新 z-index

$widget2.sortable({
    ...
    change: function () {
       ...
       $widget2.reverseZIndex();
    }
    ...
});

【讨论】:

  • 谢谢,这完美无缺。我只需要更改更改方法以停止排序以使其正常工作。
【解决方案2】:

使用nthhttp://codepen.io/anon/pen/pvEdMw

HTML

<ul>
<li >aaa</li>
<li>aaaasdsd</li>
<li>fgf</li>
</ul>

CSS

li{
 background-color:orange;
 }

li:nth-child(n-3){
color:red;
}

li:nth-child(n+2){
color:blue;
} 

li:nth-child(n+3){
color:green;
}

JQUERY

$('ul').sortable();

【讨论】:

  • 这是一个很好的解决方案,谢谢。但是有一个问题,我不知道我的列表会有多少元素,可能有 10 个或 100 个。
  • @vadimyer 如果您使用两种颜色,则可以将其设置为li:nth-child(odd)even
  • 很遗憾我需要使用 z-indexes。
  • @vadimyer 你可以使用z-index
  • 我有盒子阴影,需要它们位于每个下一个元素的顶部。不过,我很乐意为您的解决方案投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多