Javascript change Div style

后端 未结 7 1702
轻奢々
轻奢々 2021-01-03 18:30

I want that part 1 onclick div style changes and part 2 again on click it comes back to normal. I tried doing so but I failed to achieve the

相关标签:
7条回答
  • 2021-01-03 18:40
    function abc() {
        var color = document.getElementById("test").style.color;
        if (color === "red")
             document.getElementById("test").style.color="black";
        else
             document.getElementById("test").style.color="red";
    }
    
    0 讨论(0)
  • 2021-01-03 18:49

    you may check the color before you click to change it.

    function abc(){
         var color = document.getElementById("test").style.color;
         if(color==''){
             //change
         }else{
             //change back
         }
    }
    
    0 讨论(0)
  • 2021-01-03 18:50

    Have some logic to check the color or have some flag,

    function abc() {
        var currentColor = document.getElementById("test").style.color;
    
        if(currentColor == 'red'){
        document.getElementById("test").style.color="black";
        }else{
       document.getElementById("test").style.color="red";
    
        }
    }
    
    0 讨论(0)
  • 2021-01-03 18:53

    Using jQuery:

    $(document).ready(function(){
        $('div').click(function(){
            $(this).toggleClass('clicked');
        });
    });​
    

    Live example

    0 讨论(0)
  • 2021-01-03 18:54

    Better change the class of the element (.regular is black, .alert is red):

    function abc(){
      var myDiv = document.getElementById("test");
      if (myDiv.className == 'alert') {
        myDiv.className = 'regular';
      } else {
        myDiv.className = 'alert';
      }
    }
    
    0 讨论(0)
  • 2021-01-03 19:03
    function abc() {
        var color = document.getElementById("test").style.color;
        color = (color=="red") ? "black" : "red" ;
        document.getElementById("test").style.color= color;
    }
    
    0 讨论(0)
提交回复
热议问题