切换color-scheme时JS控制的div背景色无法自动更新求助
解决方案
问题出在你只在页面初始化时获取了一次CSS变量的值,之后切换主题时没有重新获取并更新change-with-js元素的背景色。另外,自动模式下需要移除color-scheme属性,让媒体查询的设置生效。以下是修复后的原生JS方案:
<html> <head> <style> html { --background-light : #F5F5F6; --background-dark : #1D1D1F; } :root { color-scheme: light; --background : var(--background-light); } @media (prefers-color-scheme: dark) { :root { color-scheme: dark; --background : var(--background-dark); } } [color-scheme="light"] { color-scheme : light; --background : var(--background-light); } [color-scheme="dark"] { color-scheme : dark; --background : var(--background-dark); } .mydivs { width : 100vw; height : 100vh; } #change-with-css { background : var(--background); } </style> </head> <body> <form id="color-scheme"> <div> <label for="auto">自动</label> <input checked type="radio" id="auto" class="toggler" name="theme" value="auto"/> </div> <div class="color-boxes"> <label for="light">浅色</label> <input type="radio" id="light" class="toggler" name="theme" value="light"/> </div> <div class="color-boxes"> <label for="dark">深色</label> <input type="radio" id="dark" class="toggler" name="theme" value="dark"/> </div> </form> <div id="change-with-css" class="mydivs"></div> <div id="change-with-js" class="mydivs"></div> <script> const switcher = document.querySelector("#color-scheme"); const doc = document.firstElementChild; const myJsDiv = document.querySelector("#change-with-js"); // 更新JS控制元素的背景色 function updateJsElementTheme() { const computedStyle = getComputedStyle(document.documentElement); const bgColor = computedStyle.getPropertyValue("--background").trim(); myJsDiv.style.background = bgColor; } // 设置主题 const setTheme = (theme) => { if (theme === "auto") { doc.removeAttribute("color-scheme"); } else { doc.setAttribute("color-scheme", theme); } updateJsElementTheme(); // 切换后立即更新 }; // 监听单选按钮切换 switcher.addEventListener("input", (e) => setTheme(e.target.value)); // 监听系统主题变化(自动模式下生效) window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => { const selectedTheme = switcher.querySelector('input[name="theme"]:checked').value; if (selectedTheme === "auto") { updateJsElementTheme(); } }); // 初始化时设置一次 updateJsElementTheme(); </script> </body> </html>
关键修改点:
- 新增
updateJsElementTheme函数:每次主题变化时,重新获取:root的计算样式里的--background变量,更新JS控制的div背景色。 - 修复
setTheme函数:选择auto时移除color-scheme属性,让媒体查询的系统主题设置生效,同时调用更新函数。 - 监听系统主题变化:在自动模式下,当系统切换浅色/深色主题时,自动更新JS元素的背景。
- 初始化调用更新函数:确保页面加载时JS元素的背景和当前主题一致。
内容的提问来源于stack exchange,提问作者Robith Nuriel Haq
相关产品推荐
相关产品推荐

