CSS 和 Javascript:更改颜色效果悬停样式的功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16365919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:44:06  来源:igfitidea点击:

CSS and Javascript: Function to change color effects hover style

javascriptcssonclickhover

提问by user2219915

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?

我有一个元素,我在其中为 CSS 中的悬停状态设置了文本颜色和不同的文本颜色。我有一些 javascript,因此当我单击元素时,它会更改元素的文本颜色。它工作正常,除了它还会影响悬停 CSS,我希望它与预单击的悬停 CSS 保持相同。无论如何要阻止悬停 css 受到影响或设置悬停 CSS?

http://jsfiddle.net/77zg8/

http://jsfiddle.net/77zg8/

CSS:

CSS:

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

HTML:

HTML:

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

Javascript:

Javascript:

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

回答by Denys Séguret

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

而不是直接设置颜色,它会更干净(使用类更有效)。

CSS :

CSS :

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

JavaScript :

JavaScript :

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

demonstration

示范

回答by epascarello

Use classes!

使用类!

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

Basic JavaScript:

基本 JavaScript:

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

Of course you would have to toggle the classes.

当然,您必须切换课程。

回答by mikeswright49

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

您遇到的问题是 css 中的特异性概念。特异性控制应用哪些规则以及应用的顺序。因为 javascript 更新了样式元素,它将覆盖特定性并删除所有先前关于颜色样式的规则。所以改为向元素添加一个类,例如“单击”。点击的地方是你的新颜色

.clicked{color:red}

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

This will do what you need.

这将满足您的需求。

回答by Anoop

You can use !importantJSFIDDLE

您可以使用!importantJSFIDDLE

#test:hover {color:green!important;}