代码之家  ›  专栏  ›  技术社区  ›  Sp0tlight

JavaScript-动态加载的CSS:CSS变量对JS不可见,但从CSS中得到评估

  •  0
  • Sp0tlight  · 技术社区  · 7 年前

    我通过JavaScript将一些样式表动态加载到我的应用程序中。在这个样式表中,我有不同的CSS变量,我想从我的JS中读/写。

    在运行时动态加载的样式表确实有一些奇怪的错误。CSS变量由CSS计算,但

    有人有提示吗?

    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');
    

    :root {
      --foo: green
    }
    
    #foo {
      background-color: var(--foo);
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Terry    7 年前

    这是因为样式表没有在运行时加载,因此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