Angular2 dynamic change CSS property

前端 未结 5 1348
粉色の甜心
粉色の甜心 2020-12-01 02:07

We are making an Angular2 application and we want to be able to somehow create a global CSS variable (and update the properties\' values whenever changed wh

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 02:37

    Just use standard CSS variables:

    Your global css (eg: styles.css)

    body {
      --my-var: #000
    }
    

    In your component's css or whatever it is:

    span {
      color: var(--my-var)
    }
    

    Then you can change the value of the variable directly with TS/JS by setting inline style to html element:

    document.querySelector("body").style.cssText = "--my-var: #000";
    

    Otherwise you can use jQuery for it:

    $("body").css("--my-var", "#fff");
    

提交回复
热议问题