簡體   English   中英

jQuery UI可排序:如何保持更改項的CSS值不變?

[英]jQuery UI sortable: how to leave css values of changed items untouched?

我有一個以相反順序設置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索引不變時實現效果。 說,我要按以下順序對所有代表的項目進行排序:第二,第三,第一。 但是請保持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);
        }
    });

使用nth孩子http://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();

由於您已經在頁面上使用過JavaScript,所以我建議您使用此小jQuery插件計算並z-index准備就緒的文檔分配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(...);
});

然后,您可以在任何給定列表<ul><ol> (甚至是父級<div> )上使用此插件,因此子級的z-index的順序相反。

在jQuery上對change進行排序,以更新z-index

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM