交互需求
- 默認態:標籤並排顯示,無刪除按鈕
- 點擊「編輯」鏈接 → 所有標籤顯示右上角「×」刪除按鈕,鏈接文字變「完成」
- 點擊「×」 → 確認後移除該標籤
- 點擊「完成」 → 隱藏所有「×」,鏈接文字還原「編輯」
核心 CSS:相對定位容器 + 絕對定位刪除按鈕
#tags { overflow: hidden; font-size: 13px; margin-top: 10px; }
#tags div { float: left; margin-right: 10px; position: relative; border: 1px dotted #999; padding: 2px 20px 2px 5px; }
#tags div a { position: absolute; right: 0; top: -10px; display: none; background: #000; color: #fff; padding: 0 5px; text-decoration: none; }
/* 編輯模式下顯示刪除按鈕 */
#tags div.edit a { display: block; }
HTML 結構
<a href="javascript:void(0)" onclick="toggleEdit(this)">編輯</a>
<div id="tags">
<div>標籤1<a href="#">×</a></div>
<div>標籤2<a href="#">×</a></div>
<div>標籤3<a href="#">×</a></div>
</div>
jQuery 邏輯(含刪除確認)
function toggleEdit(link) {
const isEdit = link.innerHTML === '編輯';
link.innerHTML = isEdit ? '完成' : '編輯';
$('#tags div').toggleClass('edit', isEdit); // 添加/移除 .edit 類
}
$(function() {
// 事件委派:動態新增的標籤也生效
$('#tags').on('click', 'a', function(e) {
e.preventDefault();
if (confirm('確認刪除?')) {
$(this).parent().remove();
}
});
});
進階:動態新增標籤
function addTag(text) {
const $tag = $(`<div>${text}<a href="#">×</a></div>`);
// 若當前處於編輯模式,自動添加 .edit 類
if ($('#tags div').hasClass('edit')) $tag.addClass('edit');
$('#tags').append($tag);
}
關鍵點總結
- 容器
position: relative,刪除按鈕 position: absolute 定位右上角
- 通過父容器
.edit 類控制子按鈕顯隱,避免遍歷 DOM
- 事件委派
$('#tags').on('click', 'a', ...) 處理動態元素
toggleClass(className, boolean) 一行切換編輯狀態