我通过 JavaScript 将一些样式表动态加载到我的应用程序中。在这个样式表中,我有不同的 CSS 变量,我想从我的 JS 读取/写入它们。
直接嵌入 head 标签的样式表被正确处理。 CSS 变量由 CSS 评估并在 JS 中可见。
在运行时动态加载的样式表确实有一些奇怪的错误。 CSS 变量由 CSS 求值,但 JS 不可见。
有人有提示吗?
具有最少错误演示的 Plunker:
https://plnkr.co/edit/EChqjvZQJp7yz3L6nknU?p=preview
我用来动态加载 CSS 的方法:
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", "not_embedded_from_start.css");
document.getElementsByTagName("head")[0].appendChild(fileref);
我用来读取CSS变量的方法:
var cS = window.getComputedStyle(document.querySelector("html"));
var pV = cS.getPropertyValue('--foo');
示例 CSS:
:root {
--foo: green
}
#foo {
background-color: var(--foo);
}
最佳答案
那是因为样式表在运行时没有完成加载,因此 CSS 变量直到稍后才能被 JS 访问。
为此,您 simply attach an onload
handler到您动态添加的样式表,以便它在加载完成时调用一个函数,比如 stylesheetLoaded()
(因此 JS 可以访问):
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.onload = function(){ stylesheetLoaded(); }
fileref.setAttribute("href", "not_embedded_from_start.css");
请注意,强烈建议在设置href
属性之前附加onload
处理程序。
然后您可以在该函数调用中执行您想要的任何逻辑:
var stylesheetLoaded = function() {
cS = window.getComputedStyle(document.querySelector("html"));
pV = cS.getPropertyValue('--baz');
document.getElementById("baz").innerText = pV;
}
查看代码的概念验证分支:https://plnkr.co/edit/OYXk7zblryLs3F5VM51h?p=preview
关于JavaScript - 动态加载的 CSS : CSS variable not visible for JS but gets evaluated from CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45241154/