CSS and [removed] Function to change color effects

2019-01-26 17:43发布

I have an element where I set a text color and a different text color for the hover state in the CSS. I have some javascript so that when I click the element, it changes the text color of the element. It works fine except that it also effects the hover CSS which I want to remain the same as the pre-clicked hover CSS. Is there anyway to either stop the hover css from being effected or to set the hover CSS?

http://jsfiddle.net/77zg8/

CSS:

#test {color: blue;}
#test:hover {color:green;}

HTML:

<div id="test" onClick="javascript:change()">qwerty</div>

Javascript:

function change() {document.getElementById("test").style.color="#cc0000";};

4条回答
爷、活的狠高调
2楼-- · 2019-01-26 18:19

You can use !important JSFIDDLE

#test:hover {color:green!important;}
查看更多
Juvenile、少年°
3楼-- · 2019-01-26 18:30

Instead of setting the color directly, it would be cleaner (and more effective to use a class).

CSS :

#test {color: blue;}
#test.active {color:red;}
#test:hover {color:green;}

JavaScript :

function change() {
   document.getElementById("test").className='active';
}

demonstration

查看更多
何必那么认真
4楼-- · 2019-01-26 18:34

The issue that you are running into is the concept of specificity in css. Specificity controls what rules get applied and in what order. Because the javascript updates the style element, it will override the specificity and erase all previous rules regarding the color styling. so instead add a class eg "clicked" to the element. where clicked is your new color

.clicked{color:red}

function change() {document.getElementById("test").class += " clicked"};

This will do what you need.

查看更多
Explosion°爆炸
5楼-- · 2019-01-26 18:36

Use classes!

#test {color: blue;}
#test:hover, #test.foo:hover {color:green;}
#test.foo { color : #cc0000 }

Basic JavaScript:

function change() {document.getElementById("test").className = "foo"; };

Of course you would have to toggle the classes.

查看更多
登录 后发表回答