如何从StyleSheet中按名称获取CSS类?

我有以下代码使用索引来获取样式表以及该样式表中的css类。

for (var s = document.styleSheets.length - 1; s >= 0; s--) { if (document.styleSheets[s].href && (document.styleSheets[s].href.indexOf("MySheet.css")!=-1)) { var cssRules = document.styleSheets[s].cssRules || document.styleSheets[s].rules || []; // IE support for (var c = 0; c < cssRules.length; c++) { if (cssRules[c].selectorText === ".myclass ") cssRules[c].style.backgroundColor = 'powderblue'; } } } 

虽然我在上面的代码中通过它的名字得到CSS类,但我需要避免这种循环。是否有可能通过查询来获取CSS类?如何做到这一点?还有其他一些方法来避免这种循环?

这是一个片段,可用于创建新规则和操作样式表中的现有规则。 特定工作表由其title识别,因此您需要为要操作的样式表提供唯一标题(将title属性添加到相应的linkstyle标记)。

 function CssManipulator (sheetTitle) { var that = this, // A reference to an instance len = document.styleSheets.length, // Caches the length of the collection n; // General loop counter this.styleSheet = null; // Stores the stylesheet for the instance this.selectors = {}; // Stores the selectors we've handled this.cssRules = null; // Caches cssRules of the given stylesheet // Search the given stylesheet by title and assign it and its cssRules to instance properties for (n = 0; n < len; n++) { if (document.styleSheets[n].title === sheetTitle) { this.styleSheet = document.styleSheets[n]; this.cssRules = document.styleSheets[n].cssRules || document.styleSheets[n].rules; break; } } // Changes properties of the given selector this.change = function (selector, prop, value) { // FF knows only camel-cased propertynames, hence camel-casing the propName var propName = (prop.charAt(0) === '-') ? prop.substring(1, prop.length) : prop; propName = propName.replace(/-([az])/gi, function(str, chr) { return chr.toUpperCase(); }); if (selector in that.selectors) { // Change the rule, if we've handled this selector before that.styleSheet.cssRules[that.selectors[selector]].style[propName] = value; } else { // Add a new rule if we haven't met this selector before that.selectors[selector] = that.styleSheet.insertRule(selector + '{' + prop + ':' + value + ';}', that.cssRules.length); } }; } 

selectors包含魔术,它存储insertRule返回的新创建规则的insertRule

用法

为每个要更改的样式表创建一个CssManipulator实例,如下所示:

 pageSheet = new CssManipulator('title_of_the_stylesheet'); 

然后,您可以通过调用对象的change方法来操作样式表中的大多数规则(使用此代码无法操作伪元素):

 pageSheet.change('.some_selector', 'property-name', 'value_for_the_property'); 

如果传递的选择器存在于原始样式表中,则此方法会添加一个新的选择器。 请注意,如果更改属性名称(如background-color ,则需要将属性名称的“连字模式”传递给方法。

您可以进一步开发对象,例如,可以轻松更改change方法以接受每个调用的多个属性 - 值对。

如果我理解正确,你想改变CSS。 确切地说,您希望更改类的CSS规则。 要做到这一点,并且要提高效率,我会用你的选择器创建一个样式表,例如,它可能只是.selector>div{}或者只是.selector{}

  

我前一段时间用这个来制作我的桌子方格(而我的细胞都相等)。

然后我使用此代码更改样式表中类的参数。

 document.styleSheets[0].cssRules[numberOfSelector].style.height=document.querySelector('.squerify td').offsetWidht+"px"; 

这是我能想到的最佳方式,但如果你愿意,你可以使用循环来搜索类。
如果误解了您的问题,请发表评论。

 var someVar = document.querySelectorAll('.someClass'); for(var i=0; i 

这将使用类'someClass'获取所有元素并更改背景颜色。