You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现选项卡及颜色按钮选中状态保留与开关功能

代码调整方案

1. 新增CSS样式

用于控制按钮选中状态的视觉表现,你可以根据需求调整样式细节:

/* 选项卡按钮选中样式 */
.tabButton.active {
    background-color: #1677ff;
    color: #fff;
    border: 1px solid #1677ff;
}
/* 颜色按钮基础样式 */
.paletteButton {
    width: 32px;
    height: 32px;
    border: 2px solid #eee;
    cursor: pointer;
    margin-right: 4px;
}
/* 颜色按钮选中样式 */
.paletteSelect {
    border-color: #000;
}
/* 待变色的div基础样式,方便预览效果 */
#change1, #change2 {
    width: 120px;
    height: 120px;
    margin: 12px 0;
    border: 1px solid #ddd;
}

2. 修改HTML中选项卡按钮的传参

给toggle_tab方法新增当前按钮实例的参数,方便控制选中状态:

<button class="tabButton" onclick="toggle_tab('tabOne', this);">Tab One</button>
<button class="tabButton" onclick="toggle_tab('tabTwo', this);">Tab Two</button>

3. 调整JavaScript逻辑

选项卡切换逻辑修改

function toggle_tab(id, currentBtn) {
    const targetTab = document.getElementById(id);
    if (!targetTab) return;

    // 判断当前点击的选项卡是否已经处于激活状态
    const isOpened = currentBtn.classList.contains('active');

    // 先清空所有选项卡的选中状态,隐藏所有选项卡内容
    document.querySelectorAll('.tabButton').forEach(btn => btn.classList.remove('active'));
    document.querySelectorAll('.clickedTab').forEach(tab => tab.style.display = 'none');

    // 如果之前未激活,则展示当前选项卡并标记按钮为选中
    if (!isOpened) {
        currentBtn.classList.add('active');
        targetTab.style.display = 'block';
    }
}

颜色按钮选中逻辑修改

解决同组颜色按钮选中状态无法取消的问题:

const divOne = document.getElementById('change1');
const divTwo = document.getElementById('change2');

document.querySelectorAll('#paletteOne button').forEach(el => {
    el.addEventListener('click', () => {
        divOne.style.backgroundColor = el.style.backgroundColor;
        // 清空同组所有颜色按钮的选中状态
        document.querySelectorAll('#paletteOne .paletteSelect').forEach(item => {
            item.classList.replace('paletteSelect', 'paletteButton');
        });
        // 标记当前按钮为选中
        el.classList.replace('paletteButton', 'paletteSelect');
    });
});

document.querySelectorAll('#paletteTwo button').forEach(el => {
    el.addEventListener('click', () => {
        divTwo.style.backgroundColor = el.style.backgroundColor;
        // 清空同组所有颜色按钮的选中状态
        document.querySelectorAll('#paletteTwo .paletteSelect').forEach(item => {
            item.classList.replace('paletteSelect', 'paletteButton');
        });
        // 标记当前按钮为选中
        el.classList.replace('paletteButton', 'paletteSelect');
    });
});

内容的提问来源于stack exchange,提问作者ShamBham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:15:03