在动态主题切换的网页开发中,我们经常需要根据不同的主题模式(例如,Bootstrap的data-bs-theme
属性)来设置不同的CSS变量。本文介绍一种方法,在不修改当前页面主题的前提下,通过JavaScript获取其他主题模式下的CSS变量值。
Bootstrap的CSS代码片段示例:
:root, [data-bs-theme=light] { --bs-body-color: #212529; } [data-bs-theme=dark] { --bs-body-color: #dee2e6; }
获取当前主题CSS变量的方法很简单:
const body = document.body; const getRealColor = () => window.getComputedStyle(body).getPropertyValue('--bs-body-color'); console.log(getRealColor());
然而,如何获取其他主题(例如,在浅色模式下获取深色模式的--bs-body-color
)的值呢? 我们需要解析CSS规则。以下代码提供了一种解决方案:
// 获取所有样式表 const stylesheets = Array.from(document.styleSheets); // 存储不同主题模式下的CSS变量 const themeVariables = { light: {}, dark: {} }; // 遍历所有样式表 stylesheets.forEach(sheet => { try { // 获取CSS规则 const rules = sheet.cssRules || sheet.rules; if (!rules) return; // 遍历规则 Array.from(rules).forEach(rule => { if (rule.selectorText) { // 匹配主题选择器 if (rule.selectorText === ':root' || rule.selectorText === '[data-bs-theme="light"]') { // 提取light主题变量 const style = rule.style; for (let i = 0; i < style.length; i++) { const prop = style[i]; themeVariables.light[prop] = style.getPropertyValue(prop); } } else if (rule.selectorText === '[data-bs-theme="dark"]') { // 提取dark主题变量 const style = rule.style; for (let i = 0; i < style.length; i++) { const prop = style[i]; themeVariables.dark[prop] = style.getPropertyValue(prop); } } } }); } catch (e) { console.error('Error accessing stylesheet:', e); } }); console.log('Theme Variables:', themeVariables); // 访问深色模式下的 --bs-body-color: console.log(themeVariables.dark['--bs-body-color']);
这段代码遍历所有样式表,查找':root'
, '[data-bs-theme="light"]'
和 '[data-bs-theme="dark"]'
选择器,并提取对应的CSS变量,存储在themeVariables
对象中。 您可以根据需要访问不同主题下的变量。 请注意错误处理部分,以应对可能出现的跨域或样式表访问错误。
通过这种方法,我们可以在不影响当前页面主题显示的情况下,获取其他主题模式下的CSS变量值,从而实现更灵活的主题管理和动态样式调整。