从其他主题模式获取 css 变量的值
bootstrap 使用 css 变量 (如 --bs-body-color) 来控制其组件的外观。然而,默认情况下,只能通过 js 获取当前主题模式的 css 变量值。
解决方案:解析 css
为了获取其他主题模式的 css 变量值,一种方法是解析 css 文件,从中提取变量信息。这可以通过以下步骤实现:
- 创建一个 js 函数来加载 css 文件。
- 使用 domparser 解析 css 文件并提取样式表。
- 循环遍历样式表规则,并从规则中解析 css 变量。
示例代码
您可以使用以下 js 代码实现此解决方案:
function getcssvariablevalue(variablename, themename) {
const cssfileurl = '<path/to/the/css/file>'; // 替换为实际的 css 文件路径
// 加载并解析 css 文件
const xhr = new xmlhttprequest();
xhr.open('get', cssfileurl, true);
xhr.send();
const stylesheets = document.adoptnode(xhr.responsexml.documentelement);
// 从样式表中提取变量
const rules = stylesheets.stylesheets[0].cssrules;
for (let i = 0; i < rules.length; i++) {
const rule = rules[i];
if (rule.selectortext == '[data-bs-theme=' + themename + ']') {
for (let j = 0; j < rule.style.length; j++) {
const property = rule.style[j];
if (property == variablename) {
return rule.style.getpropertyvalue(property);
}
}
}
}
return null;
}使用
要获取其他主题模式的 css 变量值,您可以调用 getcssvariablevalue 函数,并传入变量名称和主题名称:
console.log(getCSSVariableValue('--bs-body-color', 'dark'));

