
接到一个需求,表格的可拖拽排序,对一个表格的tr进行排序,用户比较容易接受并且操作的表格排序也就拖拽排序表格吧。
需要用到jQuery、jQuery-ui
话不多说上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
</style>
<body>
<table id="sort" class="grid" title="Kurt Vonnegut novels">
<thead>
<tr>
<th class="index">No.</th>
<th>Year</th>
<th>Title</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td class="index">1</td>
<td>1969</td>
<td>Slaughterhouse-Five</td>
<td>A+</td>
</tr>
<tr>
<td class="index">2</td>
<td>1952</td>
<td>Player Piano</td>
<td>B</td>
</tr>
<tr>
<td class="index">3</td>
<td>1963</td>
<td>Cat‘s Cradle</td>
<td>A+</td>
</tr>
<tr>
<td class="index">4</td>
<td>1973</td>
<td>Breakfast of Champions</td>
<td>C</td>
</tr>
<tr>
<td class="index">5</td>
<td>1965</td>
<td>God Bless You, Mr. Rosewater</td>
<td>A</td>
</tr>
</tbody>
</table>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="./lib/jquery-ui.min.js"></script>
<script type="text/javascript">
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) {
console.log(e, ui)
$(‘td.index‘, ui.item.parent()).each(function (i) {
$(this).html(i + 1);
});
};
$("#sort tbody").sortable({
cursor: "move", //菱形鼠标
axis: "y", //只在y轴拖动
items: "tr", //拖拽对象
opacity: 0.5, //拖动时,透明度为0.6
revert: false, //释放时,增加动画
cancel: "tfoot,thead", //禁止表头和表未拖拽
helper: fixHelperModified,
stop: updateIndex
}).disableSelection();
//helper: fixHelperModified,这个函数的作用是:克隆你正在拖动的tr,然后依次设置你克隆的那个tr的td的宽度,使之拖动时的宽度与原来一致。也就是说,不回调这个函数也可以,就是拖动的时候tr中的单元格宽度会变小。当然了不影响放手后的宽度。
//stop: updateIndex,这个函数的作用是,拖动后维护现在索引(即第一列的值)。
</script>
</body>
</html>
原文:https://www.cnblogs.com/jskinoa/p/13731534.html