使用 javascript 修改 css 规则对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13528512/
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-24 12:17:58  来源:igfitidea点击:

modify a css rule object with javascript

javascriptcssoocss

提问by jonBreizh

Possible Duplicate:
Changing a CSS rule-set from Javascript

可能的重复:
从 Javascript 更改 CSS 规则集

I was wondering if there is any possibility to modify Css stylesheet declarations without going for inline styling.

我想知道是否有可能在不进行内联样式的情况下修改 Css 样式表声明。

Here is a quick example :

这是一个快速示例:

<style>
    .box {color:green;}
    .box:hover {color:blue;}
</style>

<div class="box">TEXT</div>

That gives a blue written box that turns green written on hover.

这给出了一个蓝色的书写框,在悬停时变为绿色。

If I give inline styling for the color, the hover behavior will be lost :

如果我为颜色提供内联样式,则悬停行为将丢失:

<div class="box" style="color:red;">TEXT</box>

That gives a red written box, no matter what.

无论如何,这都会给出一个红色的书写框。

So my question is, how can one access and modify the css declaration object rather than overwriting styles with inline ones.

所以我的问题是,如何访问和修改 css 声明对象而不是用内联样式覆盖样式。

Thanks,

谢谢,

回答by Asad Saeeduddin

You could use the cssRuleson the DOM stylesheet object corresponding to your original stylesheet to modify your rule.

您可以使用与cssRules原始样式表对应的 DOM 样式表对象来修改规则。

var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;

rules[0].style.color = 'red';

Note that IE uses rulesinstead of cssRules.

请注意,IE 使用rules而不是cssRules.

Here is a demonstration: http://jsfiddle.net/8Mnsf/1/

这是一个演示:http: //jsfiddle.net/8Mnsf/1/

回答by Kemal Da?

Just define your classes, and assign/remove classes to HTML elements with javascript.

只需定义您的类,并使用 javascript 为 HTML 元素分配/删除类。

Directly assigning style to an element, has highest priority, It will override all other CSS rules.

直接为元素分配样式,具有最高优先级,它将覆盖所有其他 CSS 规则。

EDIT: you may want to use cssText property, see example here cssText property

编辑:您可能想要使用 cssText 属性,请参阅此处的示例cssText 属性