对列表进行排序,但保留CSS标记

Sorting list but retaining the CSS markup

本文关键字:保留 CSS 标记 排序 列表      更新时间:2023-09-26

简介

我目前有一个列表(包括ulli(。

它可以使用jQuery:进行排序

$( "#sortable1" ).sortable({
    update : function () {
    var items = $('#sortable1').sortable('serialize');
    alert(items);                       
    }
});
$( "#sortable1" ).disableSelection();

问题

这段代码移动了完整的li项(包括它的类,从而移动了它的标记(。

问题

有什么方法可以匹配目标的目标类吗?我在这里设置了一个演示:http://tinker.io/65292

所以基本上,当item 1向下移动一个位置时,item 1应该变成绿色,item 2应该变成red

此外,当将item 1向下移动两个位置时,item 1应为黄色,item 2应为红色,最后item 3应为绿色。

这个演示列表只存在四个项目,但实际上这可能是任何数字。

演示代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Sortable - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <style>
  #sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
  #sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
  #sortable li span { position: absolute; margin-left: -1.3em; }
    .first { background-color: red; }
    .middle1 { background-color: green; }
    .middle2 { background-color: yellow; }
    .last { background-color: blue; }
  </style>
  <script>
  $(function() {
    $( "#sortable" ).sortable();
    $( "#sortable" ).disableSelection();
  });
  </script>
</head>
<body>
<ul id="sortable">
  <li class="first"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
  <li class="middle1"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
  <li class="middle2"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
  <li class="last"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li>
</ul>

</body>
</html>

链接:http://tinker.io/65292

使用第n个子css伪类。。。

 #sortable li:nth-child(1) { background-color: red; }
#sortable li:nth-child(2) { background-color: green; }
#sortable li:nth-child(3) { background-color: yellow; }
#sortable li:nth-child(4)  { background-color: blue; }

将css更改为基于索引而非类的目标列表元素,它将自动更新:

#sortable li:first-child { background-color: red; }
#sortable li:nth-child(2) { background-color: green; }
#sortable li:nth-child(3) { background-color: yellow; }
#sortable li:last-child { background-color: blue; }

TINKER

jQueryUI的Sortable基于移动整个DOM元素的原理。

正如您正确地注意到的,整个DOM对象被移动,包括它的所有内容和所有属性,以及它的类。

我想到了几种方法:

  1. 更改您的CSS,使其不需要<li>s上的类。可以使用纯CSS使第一个红色、第二个绿色等。您可以以各种方式使用nth-child+~选择器。然后移动<li> s是可以的,当它们落到位时的外观将是正确的
  2. 使用javascript在每个元素移动后直接删除并重新应用类