Change CSS root variable with jquery or javascript

后端 未结 2 948
我寻月下人不归
我寻月下人不归 2021-01-02 16:39

I am using CSS variables in my webpage and making a sort of theme color,

:root {
    --themeColor: #0afec0;
    --hoverColor: #fff;
    --bodyColor:  #EEF1EF         


        
2条回答
  •  失恋的感觉
    2021-01-02 16:48

    You can do it in jquery as follows (using the same example of caramba):

    $(':root').css('--themeColor', (color = ["red", "green", "lime", "purple", "blue"])[Math.floor(Math.random() * color.length)]);
    :root {
      --themeColor: orange;
    }
    
    a {
      color: var(--themeColor)
    }
    
    div {
      width: 100px;
      height: 100px;
      background-color: var(--themeColor);
    }
    
    Hello world
    
    Test

    This may not work on all versions of JQuery!

提交回复
热议问题