Change the Background of all Elements in a Class

前端 未结 5 1954
慢半拍i
慢半拍i 2021-01-28 05:25

I have a div, when I clicked on it, should turn all the elements in the .counter class to red, but at the moment it does nothing. I believe you have to run through a loop first

5条回答
  •  独厮守ぢ
    2021-01-28 05:56

    A simpler way would be to have a css variable. The code only needs to change the value of the variable and any class that uses the variable is updated automatically.

    For example:

    function myFunction(c) {
      document.documentElement.style.setProperty("--counterbg", c);
    }
    :root {--counterbg: orange;}
    
    .counter {
      width: 100px;
      height:100px;
      background-color:var(--counterbg);
    }
    #btn {
      width:100px;
      height:50px;
      position:relative;
      display:inline;
    }
    
    
    




    The variable is defined at the top of the STYLE tag and on the :root element. The .counter style references it using var(--counterbg) (these variables must start with --). The js just needs to change the value of the variable. In this example, I've done three buttons that change the variable to one of three different colours.

提交回复
热议问题