使用JavaScript或jQuery修改CSS规则?

问题描述:

是否可以使用javascript或jquery编辑/修改现有的css规则?例如,样式表有以下类:

Is it possible to edit/modify existing css rules using javascript or jquery? For instance, the stylesheet has this class:

.red {
    color: red;
}

我有10个元素。

我想做的是编辑类:

.red {
    color: blue;
}

这样也会影响同一个类的未来实例。 (第11,第12,第13个元素等)。

So that it will also effect the future instances of the same class. (11th, 12th, 13th elements and so on).

Javascript提供了document.stylesheets集合, a href =https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet =nofollow> CSSStyleSheet 对象。你可以遍历这个集合,找到你感兴趣的任何特定的css规则,并修改它的规则。

Javascript provides the document.stylesheets collection which provides a list of CSSStyleSheet objects. You can traverse this collection to find any specific css rule you are interested in and modify its rules.

但是,如前所述,这可能不是正确的方法你正在试图实现。

However, as mentioned before me this is probably not the correct approach for what you are trying to achieve. It can be a bit browser depenedant and just feels hacky.

你最好拥有两条独立的规则

You would be better off having 2 separate rules

.red { color :red }
.blue { color : blue }

在你的javascript中保存一个变量,它保存你的元素的当前默认类,即。 current_class ='blue'。当你创建一个简单的元素.addClass(current_class)。当你想改变所有的元素,.toggleClass(current_class,new_class)。

Inside your javascript maintain a variable that holds the current default class for your elements, ie. current_class = 'blue'. When you create an element simply .addClass(current_class). When you want to change all the elements, .toggleClass(current_class, new_class).