jQuery UI 实例 - 排序(Sortable)
2026/6/3 5:56:17 网站建设 项目流程

jQuery UI Sortable(排序)实例

jQuery UI 的Sortable交互允许用户通过鼠标拖拽对列表项进行排序,非常适合实现任务管理、菜单排序、看板(Kanban)等功能。它基于 Draggable 和 Droppable 构建,支持占位符、连接列表等高级特性。

推荐查看官方演示:https://jqueryui.com/sortable/

下面提供几个渐进实例,从基础到高级,代码使用最新 CDN,可直接复制到 HTML 文件测试。

1.基础排序示例

拖拽列表项改变顺序。

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI Sortable 基础示例</title><linkrel="stylesheet"href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css"><scriptsrc="//code.jquery.com/jquery-3.6.0.min.js"></script><scriptsrc="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script><style>#sortable{list-style-type:none;margin:0;padding:0;width:300px;}#sortable li{margin:5px;padding:10px;font-size:1.2em;background:#f0f0f0;cursor:move;}#sortable li.ui-sortable-helper{background:#ffeb3b;}</style></head><body><ulid="sortable"><liclass="ui-widget-content">项目 1</li><liclass="ui-widget-content">项目 2</li><liclass="ui-widget-content">项目 3</li><liclass="ui-widget-content">项目 4</li><liclass="ui-widget-content">项目 5</li></ul><script>$(function(){$("#sortable").sortable();});</script></body></html>
2.占位符与手柄(placeholder、handle)
  • placeholder:拖拽时显示占位框。
  • handle:仅指定手柄区域可拖拽排序。
<style>.placeholder{border:2px dashed #ccc;background:#fff;height:40px;}.handle{float:left;cursor:move;margin-right:10px;}</style><ulid="sortable2"><li><spanclass="handle ui-icon ui-icon-grip-dotted-vertical"></span>仅手柄排序(带占位符)</li><!-- 更多项 --></ul><script>$("#sortable2").sortable({placeholder:"placeholder",// 占位符类handle:".handle",// 仅手柄拖拽opacity:0.7// 拖拽时半透明});</script>
3.连接列表(connectWith)

多个列表间可互相拖拽排序,常用于看板(如待办/进行中/完成)。

<divstyle="display:flex;gap:20px;"><div><h3>待办</h3><ulid="todo"class="connectedSortable"><li>任务 A</li><li>任务 B</li></ul></div><div><h3>进行中</h3><ulid="doing"class="connectedSortable"></ul></div><div><h3>完成</h3><ulid="done"class="connectedSortable"><li>任务 C</li></ul></div></div><style>.connectedSortable{min-height:200px;width:200px;border:1px solid #ccc;padding:10px;}.connectedSortable li{margin:5px;padding:10px;background:#fff;}</style><script>$(".connectedSortable").sortable({connectWith:".connectedSortable",// 连接所有同类列表placeholder:"placeholder"});</script>
4.事件回调(update、receive)与获取顺序
  • update:列表内排序变化时触发。
  • receive:从其他列表接收项时触发。
  • 使用toArray()获取当前顺序。
<p>当前顺序:<spanid="order"></span></p><script>$("#sortable").sortable({update:function(event,ui){varorder=$(this).sortable("toArray");// 获取项ID数组(需给li加id)$("#order").text(order.join(", "));console.log("新顺序:",order);}});</script>

Sortable 支持网格排序(grid)、延迟启动(delay)、禁用某些项(cancel)等更多选项。常用于后台菜单管理或任务拖拽。如果你需要保存排序到服务器的 AJAX 示例、带延迟/网格的实例,或与 Selectable 结合的多选排序,请提供更多细节!

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询