从其他主题模式获取 css 变量的值
bootstrap 使用 css 变量 (如 --bs-body-color) 来控制其组件的外观。然而,默认情况下,只能通过 js 获取当前主题模式的 css 变量值。
解决方案:解析 css
为了获取其他主题模式的 css 变量值,一种方法是解析 css 文件,从中提取变量信息。这可以通过以下步骤实现:
示例代码
立即学习“Java免费学习笔记(深入)”;
您可以使用以下 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'));
以上就是如何通过JavaScript获取Bootstrap不同主题模式下的CSS变量值?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号