Change CSS root variable with jquery or javascript

后端 未结 2 935
我寻月下人不归
我寻月下人不归 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);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <a href="#">Hello world</a>
    <div>Test</div>

    This may not work on all versions of JQuery!

    0 讨论(0)
  • 2021-01-02 17:02

    You can do this pretty easy with something like:

    document.documentElement.style.setProperty('--themeColor', 'red');
    

    Update: Not sure if the question was just about changing the color as I thought. Now I've also added a getRandomColor() example. Just to get random stuff can be a big load of work depending if you want to save the last used color by the user or so ...

    // array with colors
    var colors = [
      "red",
      "green",
      "lime",
      "purple",
      "blue"
    ];
    
    // get random color from array
    function getColor() {
       return colors[
         Math.floor(Math.random() * colors.length)
       ];
    }
    
    // Set the color from array
    document.documentElement.style.setProperty('--themeColor', getColor());
    :root {
        --themeColor: orange;
    }
    
    a {
      color: var(--themeColor)
    }
          
    div {
      width: 100px;
      height: 100px;
      background-color: var(--themeColor);
    }
    <a href="#">Hello world</a>
    <div>Test</div>

    0 讨论(0)
提交回复
热议问题