我有一个列表,其中 z 索引以相反的顺序设置:
<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);
}
});
由于您已经在页面上使用了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(...);
});
然后,您可以在任何给定的列表,<ul>
或<ol>
(甚至是父<div>
)上使用此插件,因此孩子们将以相反的顺序进行z-index
。
在 jQuery 可排序的 change
中执行相同的操作,以更新z-index
:
$widget2.sortable({
...
change: function () {
...
$widget2.reverseZIndex();
}
...
});
使用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;
}
简讯
$('ul').sortable();