CJuiSortable 封裝 jQuery UI Sortable,讓清單項目支援拖曳重新排序,適用於選單管理、任務優先級、圖片排序等場景。
<?php
Yii::app()->clientScript->registerCss('sortable', "
#sortable { list-style:none; margin:0; padding:0; width:60%; }
#sortable li { margin:2px; padding:8px; border:1px solid #ddd; background:#f7f7f7; cursor:move; }
#sortable li.ui-sortable-placeholder { border:2px dashed #2196f3; background:#e3f2fd; height:30px; visibility:visible !important; }
", 'screen', CClientScript::POS_HEAD);
?>
<h2>可排序清單</h2>
<?php $this->widget('zii.widgets.jui.CJuiSortable', array(
'id' => 'sortable',
'items' => array(
'id1' => '第一項:系統設定',
'id2' => '第二項:用戶管理',
'id3' => '第三項:權限控制',
'id4' => '第四項:日誌審計',
'id5' => '第五項:備份還原',
),
'options' => array(
'cursor' => 'n-resize', // 拖曳時游標
'handle' => '.sort-handle', // 可選:指定拖曳把手
'placeholder' => 'ui-sortable-placeholder', // 佔位樣式類別
'forcePlaceholderSize' => true,
'opacity' => 0.8,
'revert' => 200, // 動畫回位毫秒
'update' => 'js:function(event, ui) {
saveOrder();
}',
),
)); ?>
<script>
function saveOrder() {
var order = $("#sortable").sortable("toArray"); // 取得 id 陣列
console.log("新順序:", order);
$.post("'.Yii::app()->createUrl('menu/saveOrder').'", { order: order.join(",") });
}
</script>
| 選項/事件 | 說明 |
|---|---|
handle | 拖曳把手選擇器(避免內容區誤觸發) |
items | 可排序子元素選擇器(預設 '> *') |
placeholder | 佔位元素 CSS 類別 |
forcePlaceholderSize | 強制佔位元素有尺寸 |
axis | 'x'/'y'/'xy' 限制拖曳方向 |
containment | 限制拖曳範圍 |
connectWith | 連接其他 sortable 清單(跨清單拖曳) |
start | 開始拖曳 |
change | 順序變更時(拖曳中) |
update | 拖曳結束且順序已變 |
stop | 結束拖曳 |
receive | 從連接清單接收項目 |
remove | 項目移至連接清單 |
<div class="board">
<h3>待辦</h3>
<ul id="todo" class="sortable-list"><li id="t1">任務一</li></ul>
<h3>進行中</h3>
<ul id="doing" class="sortable-list"><li id="d1">任務二</li></ul>
<h3>完成</h3>
<ul id="done" class="sortable-list"></ul>
</div>
<script>
$(".sortable-list").sortable({
connectWith: ".sortable-list",
receive: function(event, ui) {
var status = $(this).attr("id"); // todo/doing/done
var taskId = ui.item.attr("id");
$.post("updateTaskStatus", { id: taskId, status: status });
}
});
</script>
// Controller
public function actionSaveOrder() {
$order = explode(',', $_POST['order']);
foreach ($order as $index => $id) {
Menu::model()->updateByPk($id, array('sort_order' => $index + 1));
}
echo CJSON::encode(array('success' => true));
}
id 必須唯一且對應資料庫主鍵connectWith 雙向設定,注意 receive/remove 事件配對