對元素進行拖動排序的實作方式有很多,本文示範如何使用 jQuery 搭配 jQuery UI 的 sortable 完成這項工作。
頁面引入 jQuery 與 jQuery UI,並放置一個待排序的列表:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.js"></script> <ul id="list"> <li id="14" title="1"><img alt="img" src="https://www.baidu.com/img/baidu_logo.gif" /></li> <li id="13" title="2"><img alt="img" src="https://www.google.com.hk/images/srpr/logo3w.png" /></li> <li id="16" title="3"><img alt="img" src="https://img3.cn.msn.com/images/0809/logo1.png" /></li> </ul>
$(document).ready(function () {
var list = $("#list"); // ul
var show = $("#show"); // 輸出提示
var orderlist = $("#orderlist"); // 原順序
var check = $("#check"); // 是否更新到數據庫
// 保存原來的排列順序
var order = [];
list.children("li").each(function () {
order.push(this.title); // 原排列順序保存在 title
$(this).attr("title", "你可以拖動進行排序");
});
orderlist.val(order.join());
// 執行排列操作
list.sortable({
axis: 'y', // 只能縱向拖動
opacity: 0.7, // 移動時的透明度
update: function () { // 排序結束且坐標改變時觸發
Submit(check.attr("checked"));
}
});
// ajax 更新
var Update = function (itemid, itemorder) {
$.ajax({
type: "post",
url: "update.aspx",
data: { id: itemid, order: orderlist.val() },
beforeSend: function () { show.html("正在更新"); },
success: function (req) {
if (req == "100") { show.html("更新成功"); }
else if (req == "001") { show.html("失敗,請稍後再試"); }
else { show.html("參數不全"); }
}
});
};
// 調用 ajax 更新方法
var Submit = function (update) {
var order = [];
list.children("li").each(function () {
order.push(this.id);
});
var itemid = order.join(',');
if (update) {
Update(itemid);
} else {
show.html("");
}
};
});
實作重點在於:先在初始化時把每個 li 的原始順序(title)存起來,呼叫 sortable() 並設定 axis: 'y' 限制縱向拖動、opacity 設定拖動透明度;在 update 事件中觸發 Submit,收集排序後各元素的 id,若勾選了更新選項就透過 AJAX 把新順序提交到後端保存,並即時顯示處理結果。