How can I conditionally change css styles with js?

前端 未结 2 1216
生来不讨喜
生来不讨喜 2021-01-06 22:35

I\'d like to implement some javascript that uses an if statement to change some css styles. Not sure how to do it, any help would be great!

相关标签:
2条回答
  • 2021-01-06 22:46

    If you want to change a single style of an element using JavaScript, use

    document.getElementById(id).style.property = new style
    

    eg :

    document.getElementById("myDiv").style.color= "red";
    

    To add a new CSS class to an element, use

    document.getElementById(id).classList.add("mystyle");
    

    To remove

    document.getElementById(id).classList.remove("mystyle");
    

    Demo :

    function changeSingleStyle() {
      var color = document.getElementById("myDiv").style.color;
      if (color === "red")
        document.getElementById("myDiv").style.color = "yellow";
      else
        document.getElementById("myDiv").style.color = "red";
    }
    function addClass() {
        document.getElementById("myDiv").classList.add("mystyle");
    }
    function removeClass() {
        document.getElementById("myDiv").classList.remove("mystyle");
    }
    .mystyle {
      color : red;
      background: green;
      font-size: 50px;
    }
    <div id="myDiv"> This is a div </div>
    <button onclick="changeSingleStyle()">changeSingleStyle</button>
    <button onclick="addClass()">addClass</button>
    <button onclick="removeClass()">removeClass</button>

    0 讨论(0)
  • 2021-01-06 22:56

    First of all, to change CSS using JavaScript, the syntax looks like the following:

    document.getElementById(id).style.property = new style
    

    For example, if you want to change the display property of an element with id = "container" to block, it would be:

    document.getElementById("container").style.display = "block";
    

    Given this, you could easily add an IF statement depending on what condition you want. For example:

    if(condition)
    {
         document.getElementById("container").style.display = "block";
    }
    
    0 讨论(0)
提交回复
热议问题