萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現同輩元素單選高亮切換效果

核心邏輯

利用 jQuery 同輩選擇器 .siblings() 或遍歷集合移除 active 類,再為當前元素添加 active 類,實現單選高亮。

完整代碼


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>同輩元素單選高亮</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <style>
        .template-list { max-width: 400px; margin: 20px auto; }
        .template-item { 
            display: block; padding: 12px 16px; margin: 8px 0; 
            background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px;
            cursor: pointer; transition: all 0.2s; text-align: center;
        }
        .template-item:hover { background: #e3f2fd; border-color: #2196f3; }
        .template-item.active { 
            background: #2196f3; color: #fff; border-color: #2196f3; 
            box-shadow: 0 2px 8px rgba(33,150,243,0.3);
        }
    </style>
</head>
<body>
    <div class="template-list" id="linktable">
        <span class="template-item active" data-id="001">模板 001 (一行三列)</span>
        <span class="template-item" data-id="002">模板 002 (一行四列)</span>
        <span class="template-item" data-id="003">模板 003 (一行三列)</span>
        <span class="template-item" data-id="004">模板 004 (一行四列)</span>
        <span class="template-item" data-id="005">模板 005 (一行三列)</span>
    </div>

    <script>
        $(function() {
            const $items = $('#linktable .template-item');
            
            $items.on('click', function() {
                const $this = $(this);
                if ($this.hasClass('active')) return; // 已選中不處理
                
                $items.removeClass('active');
                $this.addClass('active');
                
                // 觸發自定義事件,通知其他組件
                $this.trigger('template:select', [$this.data('id')]);
            });
            
            // 監聽選中事件(解耦業務邏輯)
            $items.on('template:select', function(e, templateId) {
                console.log('選中模板:', templateId);
                // 此處可觸發預覽渲染、表單更新等
            });
        });
    </script>
</body>
</html>

進階:鍵盤無障礙支援


$items.on('keydown', function(e) {
    const $items = $('#linktable .template-item');
    const index = $items.index(this);
    let targetIndex = index;
    
    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
        targetIndex = (index + 1) % $items.length;
    } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
        targetIndex = (index - 1 + $items.length) % $items.length;
    } else if (e.key === 'Home') {
        targetIndex = 0;
    } else if (e.key === 'End') {
        targetIndex = $items.length - 1;
    } else {
        return;
    }
    
    e.preventDefault();
    $items.eq(targetIndex).focus().click();
});

// 初始化 tabindex
$items.attr('tabindex', '0').first().attr('tabindex', '0').siblings().attr('tabindex', '-1');
$items.on('focus', function() {
    $items.attr('tabindex', '-1');
    $(this).attr('tabindex', '0');
});

原生 JS 實現(無依賴)


const container = document.getElementById('linktable');
const items = container.querySelectorAll('.template-item');

items.forEach(item => {
    item.addEventListener('click', () => {
        items.forEach(i => i.classList.remove('active'));
        item.classList.add('active');
        item.dispatchEvent(new CustomEvent('template:select', { 
            detail: item.dataset.id, bubbles: true 
        }));
    });
});

// 事件委託版本(動態項目)
container.addEventListener('click', e => {
    const item = e.target.closest('.template-item');
    if (item && container.contains(item)) {
        items.forEach(i => i.classList.remove('active'));
        item.classList.add('active');
    }
});

狀態管理擴展


// 獲取當前選中值
function getSelectedTemplate() {
    return $('#linktable .template-item.active').data('id') || null;
}

// 程序化選中
function selectTemplate(id) {
    $(`#linktable .template-item[data-id="${id}"]`).click();
}

// 重置
function resetSelection() {
    $('#linktable .template-item').removeClass('active').first().addClass('active');
}
copyright © 萬盛學電腦網 all rights reserved