DIV CSS 佈局教程網

jQuery 拖動排序:以 jQuery UI sortable 實作清單拖曳
編輯:JQuery特效代碼     

很多後台都需要「拖一下就能調整順序」的清單,例如首頁橫幅排序、文章置頂順序、表單欄位排序。自己從零處理 mousedown、mousemove、mouseup 加上座標換算很花時間,實際專案裡更常見的做法是直接用 jQuery UI 提供的 sortable()。

需要的資源

這個範例搭配 jQuery 1.3.2 與 jQuery UI 1.7.1 使用(這是範例原始版本的組合;實務上建議改用目前維護中的版本):

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.7.1.custom.min.js"></script>

頁面結構

左邊是可拖曳的清單,右邊是一個空容器,用來即時顯示目前排序後的 id 陣列:

<div id="contentWrap">
  <div id="contentLeft">
    <ul class="ui-sortable">
      <li id="recordsArray_1">1. Once dropped, an Ajax query is activated</li>
      <li id="recordsArray_2">2. Dragging changes the opacity of the item</li>
      <li id="recordsArray_3">3. Returned array can be found at the right</li>
      <li id="recordsArray_4">4. It is very very easy</li>
    </ul>
  </div>
  <div id="contentRight"></div>
</div>

核心腳本

$(function() {
    $("#contentLeft ul").sortable({
        opacity: 0.5,
        cursor: 'move',
        update: function() {
            var id = "";
            $("ul.ui-sortable li").each(function(){
                id += $(this).attr("id") + "<br/>";
            });
            $("#contentRight").html(id);
        }
    });
});

參數怎麼讀

三個設定各有用途。opacity: 0.5 讓被拖動的那一項變成半透明,使用者一眼就知道「手上抓的是哪一塊」;cursor: 'move' 把游標改成四向箭頭,暗示這一排可以搬;update 是關鍵回呼,只有在拖放完成、DOM 順序真的變了之後才觸發。

在 update 裡我們用 each() 依序走過所有 li,把每個元素的 id 屬性串成字串。由於 DOM 的順序此時已經是新順序,因此收集出來的 id 序列就是使用者拖完之後的結果。範例只是把它印在右側,實務上把這串 id 丟給後端存起來,就完成了一次排序保存,通常會搭配 $.post() 或 $.ajax() 送出。

實作上的經驗

把 update 裡收集 id 的邏輯抽成獨立函式,之後初始化、還原排序、送出表單時都能重複呼叫,維護起來清爽很多。另外若清單很長,建議加上 scroll: true,讓頁面在拖到邊緣時自動捲動,體驗會好很多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved