这是因为样式表没有在运行时加载,因此JS直到稍后才可以访问CSS变量。
要做到这一点,你
simply attach an
onload
handler
添加到动态添加的样式表中,以便它调用函数,例如
stylesheetLoaded()
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
属性
.
然后,您可以在该函数调用中执行您想要的任何逻辑:
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