如何通过JavaScript根据body类切换主题按钮文本?
优化明暗主题切换按钮文本的实现方案
首先,你自己写的代码存在一个语法错误:else if (document.body.classList.contains("light-theme") 缺少闭合的右括号 ),这会导致脚本无法正常运行。
下面是整合了按钮文本更新逻辑的优化方案,将文本更新与现有主题切换逻辑结合,减少重复DOM操作,同时保证初始化和每次切换后按钮文本都能正确同步:
完整代码实现
HTML
<!DOCTYPE html> <head> <meta charset="utf-8"/> <meta content="width=device-width, initial-scale=1" name="viewport"/> </head> <body> <button class="btn-toggle">Dark Mode</button> </body>
CSS(保持你原有的样式即可)
/* Default colors */ body { --text-color: #000000; --bkg-color: #ffffff; } /* Dark theme colors */ body.dark-theme { --text-color: #ffffff; --bkg-color: #000000; } /* Styles for users who prefer dark mode at the OS level */ @media (prefers-color-scheme: dark) { /* defaults to dark theme */ body { --text-color: #ffffff; --bkg-color: #000000; } /* Override dark mode with light mode styles if the user decides to swap */ body.light-theme { --text-color: #000000; --bkg-color: #ffffff; } }
JavaScript(优化后的版本)
/* Color theme picker implementation javascript */ const btn = document.querySelector(".btn-toggle"); const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)"); // 统一更新按钮文本的函数 function updateButtonText() { if (document.body.classList.contains("dark-theme")) { btn.textContent = "Light Mode"; } else if (document.body.classList.contains("light-theme")) { btn.textContent = "Dark Mode"; } else { // 处理既没有dark也没有light类的情况(比如初始状态匹配系统偏好) btn.textContent = prefersDarkScheme.matches ? "Light Mode" : "Dark Mode"; } } // 初始化主题和按钮文本 const currentTheme = localStorage.getItem("theme"); if (currentTheme === "dark") { document.body.classList.add("dark-theme"); } else if (currentTheme === "light") { document.body.classList.add("light-theme"); } else { // 没有本地存储时,根据系统偏好设置初始主题 if (prefersDarkScheme.matches) { document.body.classList.add("dark-theme"); } else { document.body.classList.add("light-theme"); } } updateButtonText(); // 初始化按钮文本 // 主题切换事件监听 btn.addEventListener("click", function () { let theme; if (document.body.classList.contains("dark-theme")) { document.body.classList.replace("dark-theme", "light-theme"); theme = "light"; } else { document.body.classList.replace("light-theme", "dark-theme"); theme = "dark"; } localStorage.setItem("theme", theme); updateButtonText(); // 切换后更新按钮文本 });
优化点说明
- 复用函数减少冗余:提取
updateButtonText函数,统一处理按钮文本更新,避免在多个地方重复编写判断逻辑。 - 简化主题切换逻辑:使用
classList.replace替代toggle,让主题切换的逻辑更清晰(确保body始终只有dark-theme或light-theme其中一个类)。 - 完善初始化逻辑:当没有本地存储时,直接根据系统偏好给body添加对应的主题类,同时同步按钮文本。
- 使用
textContent替代innerHTML:仅需更新文本内容时,textContent比innerHTML更安全、性能更好。
内容的提问来源于stack exchange,提问作者Alessandro
相关产品推荐
相关产品推荐

