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

点击同一按钮时无法移除rb类?代码问题求助

修复同一按钮点击时rb类无法移除的问题

问题出在你每次点击按钮时,都会强制给当前按钮添加rb类,不管对应的容器是否被隐藏。而容器的show类用了toggle可以切换状态,但按钮的rb类没有对应移除逻辑。

修复后的JavaScript代码

const sectionIcon = document.querySelectorAll(".nk-section-icons")
const sectionContainer = document.querySelectorAll(".nk-sec-container")
const sectionIconHover = document.querySelectorAll(".nk-section-icons")
sectionIcon.forEach((sectionBtn)=> {
    sectionBtn.addEventListener("click", (btns)=> {
        const containerTarget = btns.currentTarget.parentElement.children[1]
        const containerHoverTarget = btns.currentTarget.parentElement.children[0]

        // 重置其他容器和按钮的状态
        sectionContainer.forEach(items => {
            if(items !== containerTarget) {
                items.classList.remove("show")
            }
        })

        sectionIconHover.forEach(itemHover => {
            if(itemHover !== containerHoverTarget) {
                itemHover.classList.remove("rb")
            }
        })

        // 切换容器显示状态
        containerTarget.classList.toggle("show")
        
        // 同步按钮的rb类状态:容器显示则加类,隐藏则移除
        if (containerTarget.classList.contains("show")) {
            containerHoverTarget.classList.add("rb")
        } else {
            containerHoverTarget.classList.remove("rb")
        }
    })
})

更简洁的写法(利用toggle的第二个参数)

你也可以用classList.toggle的第二个参数来简化逻辑,它可以指定是否强制添加或移除类:

// 替换代码中最后两行
containerTarget.classList.toggle("show")
containerHoverTarget.classList.toggle("rb", containerTarget.classList.contains("show"))

这样修改后,点击同一按钮时,容器的show类被移除,按钮的rb类也会同步被移除;切换其他按钮时,旧按钮的rb类会被重置,新按钮的rb类正常添加,完全匹配容器的显示状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:20:31