简体   繁体   中英

how to toggle text color?

I need to toggle text color from red to green and vice versa.

<div id="logoup">DEEP</div>
<button id='btn'>CLICK</button>

CSS

#logoup{
    color:red;
}
.greened{
   color:green;
}

JS

$("#btn").click(function(){
    $('#logoup').toggleClass('greened');
});

Doesn't work. Console is empty.

jsfiddle

In CSS, an id's defined styles take precedence over an class's defined styles. You can simply attached the class name to the id to fix this without the the need to use !important which should only be used as a last resort:

JS Fiddle

#logoup.greened {
  color: green;
}

id occupy highers css specificity than class . So class wont be able to over rules the styles set by the id. Following changes will work

CSS

.logoup{    // id changed to class
    color:red;
}
.greened{
   color:green;
}

HTML

<div id="logoup" class="logoup">DEEP</div>
<button id='btn'>CLICK</button>

JSFIDDLE

You could use important on green , or you could control the coloring using classes, instead of applying it to the element.

Method 1: Use important! on the greened class

 $("#btn").click(function() { $('#logoup').toggleClass('greened'); }); 
 #logoup { color: red; } .greened { color: green !important; } 
 <div id="logoup">DEEP</div> <button id='btn'>CLICK</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Method 2: Don't apply color to ID, use classes

 $("#btn").click(function() { $('#logoup').toggleClass('red green'); }); 
 .red { color: red; } .green { color: green; } 
 <div id="logoup" class="red">DEEP</div> <button id='btn'>CLICK</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

When you use id instead of class you must remember about css rules prioritization. The style that has the highest CSS specificity is applied. The specificity of different elements is defined as follows:

ID attribute = 100
Class attribute = 10
Element = 1

To check this rewrite your css:

#logoup{
    color:red;
}
.greened{
   color:green!important;
}

Read about css rule priorities.

Selector Priority. Override it using !important;

 $("#btn").click(function() { $('#logoup').toggleClass('greened'); }); 
 .greened { color: green !important; } #logoup { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="logoup">DEEP</div> <button id='btn'>CLICK</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM