我通过JavaScript动态地将一些样式表加载到我的应用程序中。在这个样式表中,我有不同的CSS变量,我想从我的JS中读/写这些变量。
直接嵌入到head标记中的样式表将被正确处理。CSS变量由CSS计算,在JS中可见。
在运行时动态加载的样式表确实有一些奇怪的错误。CSS变量由CSS计算,但在JS中不可见。
有人有线索吗?
具有最小错误演示的柱塞:
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);
}发布于 2017-07-21 15:21:13
这是因为样式表不是在运行时加载的,因此CSS变量直到稍后才能被JS访问。
为此,您可以将 handler添加到动态添加的样式表中,以便在加载(因此JS可以访问)时调用函数,比如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");注意,强烈建议在设置onload 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。
https://stackoverflow.com/questions/45241154
复制相似问题