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

JavaScript明暗模式切换按钮仅能切换一次问题求助

明暗模式切换按钮无法切回亮色模式的修复方案

核心问题分析

你的代码里犯了一个基础语法错误:if/else if条件中使用了赋值运算符=,而非比较运算符===。每次点击按钮时,第一个条件会执行document.body.style.backgroundColor = 'rgb(255,255,255)'的赋值操作,这个表达式的返回值是字符串本身,会被判定为true,导致代码永远只会执行第一个代码块(切换到暗色模式),完全触发不了else if的逻辑。

另外还有一个隐藏问题:element.style只能读取元素的内联样式,如果你的默认亮色模式是通过外部CSS或<style>标签设置的,初始状态下document.body.style.backgroundColor会是空字符串,这也会导致判断逻辑失效。


基础修复版本

把条件里的=改成===,同时使用getComputedStyle获取元素实际生效的样式,避免内联样式为空的问题:

const modeButton = document.getElementById('light-dark-btn');

modeButton.addEventListener('click', () => {
    // 获取body当前实际生效的背景色
    const currentBg = getComputedStyle(document.body).backgroundColor;
    if (currentBg === 'rgb(255, 255, 255)') {
        document.body.style.backgroundColor = 'rgb(18, 18, 18)';
        document.body.style.color = 'rgb(255, 255, 255)';
    } else if (currentBg === 'rgb(18, 18, 18)') {
        document.body.style.backgroundColor = 'rgb(255, 255, 255)';
        document.body.style.color = 'rgb(0, 0, 0)';
    }
});

更优雅的实现方案(推荐)

直接操作DOM样式的方式不利于维护,建议用CSS类切换的方式,将样式逻辑完全交给CSS,JS只负责切换类名:

第一步:编写CSS样式

/* 默认亮色模式 */
body {
    background-color: rgb(255, 255, 255);
    color: rgb(0, 0, 0);
    transition: background-color 0.3s, color 0.3s; /* 添加过渡动画提升体验 */
}

/* 暗色模式样式 */
body.dark-mode {
    background-color: rgb(18, 18, 18);
    color: rgb(255, 255, 255);
}

第二步:简化JS代码

const modeButton = document.getElementById('light-dark-btn');

modeButton.addEventListener('click', () => {
    // 直接切换dark-mode类
    document.body.classList.toggle('dark-mode');
});

这种方式逻辑简洁,样式和JS完全分离,后续修改样式只需要调整CSS即可,扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:55:15