現在很多後台列表為了操作方便,都加入了拖拽排序的功能,讓使用者可以隨意調整項目的順序。這篇文章就來分享一個實用且易上手的拖拽排序方案,它基於 jQuery UI 實作。
先來看 HTML 部分,結構相當簡單:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jqueryUI拖動</title>
</head>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<style>
tr{ cursor: pointer; }
</style>
<body>
<table id="sort">
<thead>
<tr>
<th class="index">序號</th>
<th>年份</th>
<th>標題</th>
<th>作者</th>
</tr>
</thead>
<tbody>
<tr><td class="index">1</td><td>2014</td><td>這是第1個</td><td>作者甲</td></tr>
<tr><td class="index">2</td><td>2015</td><td>這是第2個</td><td>作者乙</td></tr>
<tr><td class="index">3</td><td>2016</td><td>這是第3個</td><td>作者丙</td></tr>
<tr><td class="index">4</td><td>2017</td><td>這是第4個</td><td>作者丁</td></tr>
</tbody>
</table>
</body>
</html>
除了引入 jquery.js 與 jqueryUI.js 之外,還需要加上以下這段關鍵程式碼:
$(document).ready(function(){
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index){
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function(e, ui) {
$('td.index', ui.item.parent()).each(function (i){
$(this).html(i + 1);
});
};
$("#sort tbody").sortable({
helper: fixHelperModified,
stop: updateIndex
}).disableSelection();
});
這裡有兩個重點函式:fixHelperModified 負責在拖動時讓被拖曳的列保持原本的欄寬,避免變形;updateIndex 則在拖放結束後自動重新編排序號。整體實作相當簡潔,是後台列表排序時很好用的一個方案。