技能標籤選擇、興趣愛好勾選、角色權限分配、購物車商品移動等,核心需求是兩個列表間靈活移動項目。
| 模式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 點擊切換 | 行動裝置友好、無需拖拽庫、程式碼極簡 | 批量操作不便 | 單選/少量多選、觸控螢幕 |
| 拖曳排序 | 視覺直觀、支援批量、排序自由 | 需額外庫、行動端體驗較差 | 複雜排序、桌面端後台 |
本文實現 點擊切換模式,零依賴、行動優先。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 雙向列表移動</title>
<style>
.lists { display: flex; gap: 40px; margin: 30px; }
.list-box { flex: 1; min-width: 200px; }
h3 { text-align: center; color: #333; margin-bottom: 10px; }
ul { list-style: none; padding: 0; margin: 0; border: 2px dashed #ddd; border-radius: 8px; min-height: 200px; background: #fafafa; }
li { padding: 12px 16px; margin: 8px; background: white; border: 1px solid #e0e0e0; border-radius: 4px; cursor: pointer; transition: all 0.2s; display: flex; justify-content: space-between; align-items: center; }
li:hover { border-color: #1976d2; box-shadow: 0 2px 8px rgba(25,118,210,0.15); transform: translateY(-1px); }
li::after { content: '→'; color: #999; font-size: 14px; }
#rightUL li::after { content: '←'; }
.hint { text-align: center; color: #999; padding: 20px; font-style: italic; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="lists">
<div class="list-box">
<h3>可選項目</h3>
<ul id="leftUL"><li class="hint">點擊項目移至右側</li></ul>
</div>
<div class="list-box">
<h3>已選項目</h3>
<ul id="rightUL"><li class="hint">點擊項目移回左側</li></ul>
</div>
</div>
<script>
$(function() {
const data = [
{ id: 1, name: '劉德華', age: 52 },
{ id: 2, name: '文章', age: 26 },
{ id: 3, name: '孫紅雷', age: 40 },
{ id: 4, name: '葛優', age: 58 }
];
const $left = $('#leftUL');
const $right = $('#rightUL');
// 渲染項目
function renderItem(item, $target) {
return $(`<li data-id="${item.id}">${item.name}, ${item.age}歲</li>`)
.appendTo($target)
.on('click', function() {
const $item = $(this).detach();
const isLeft = $item.parent().is($left);
$item.appendTo(isLeft ? $right : $left);
updateHints();
});
}
// 初始化
data.forEach(item => renderItem(item, $left));
// 空狀態提示
function updateHints() {
[$left, $right].forEach($ul => {
$ul.find('.hint').remove();
if ($ul.children().length === 0) {
$ul.append(`<li class="hint">${$ul.is($left) ? '點擊項目移至右側' : '點擊項目移回左側'}</li>`);
}
});
}
});
</script>
</body>
</html>
.detach() 保留事件移動const $item = $(this).detach(); // 移除但保留 click 事件
$item.appendTo(target); // 插入新位置,事件依然生效
若用 remove() 則需重新綁定事件,detach() 是移動操作的正確選擇。
const isLeft = $item.parent().is($left); // 判斷父元素是否為左列表
$item.appendTo(isLeft ? $right : $left); // 三元運算子決定目標
updateHints() 統一管理空狀態提示,避免殘留舊提示或重複添加。
// 讓 li 可聚焦並支援 Enter/Space 觸發
$item.attr('tabindex', 0).on('keydown', function(e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
$(this).trigger('click');
}
});
新增「全部移動」、「清空」按鈕,語意對應 <button>,螢幕閱讀器友好。
點擊切換模式以 detach() + appendTo() 為核心,配合事件委派與狀態同步,提供輕量、無障礙、行動友好的雙向列表交互。若需拖曳排序,建議引入 SortableJS (無依賴、15KB、支援觸控)。