本文介绍了通过名称获取CSS规则的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在样式表中找到css规则 .widget-area
的索引。
I am trying to find the index of a css rule .widget-area
in a stylesheet.
function findStyle(){
var myStylesheet=document.styleSheets[8].cssRules[".widget-area"];
console.log(myStylesheet);
};
如果我忽略了 .cssRules [。widget-area]
返回样式表的所有规则,但是有成千上万个规则。
If I leave out .cssRules[".widget-area"]
it returns all the rules of the stylesheet, but there are thousands of them.
任何人都知道该怎么做吗?
谢谢。
Anyone knows how to do this?Thanks.
推荐答案
getStyleRuleIndexBySelector
函数将找到索引特定规则。请注意,此操作仅通过选择器进行搜索,每个选择器可能有多个规则。
getStyleRuleIndexBySelector
function will find the index of a specific rule. Take into account that this searches by selector only, and there could be more than one rules per selector.
// create a dummy stylesheet which we'll search a key by value
var style = document.createElement("style")
style.appendChild(document.createTextNode(""))
document.head.appendChild(style);
// insert some rules
style.sheet.insertRule('.first{ color:red }', style.sheet.cssRules.length);
style.sheet.insertRule('.second{ color:green }', style.sheet.cssRules.length);
style.sheet.insertRule('div span a{ color:blue }', style.sheet.cssRules.length);
style.sheet.insertRule('.second{ display:none; left:1px; }', style.sheet.cssRules.length);
// get the rules
var rules = style.sheet.cssRules;
function getStyleRuleIndexBySelector(selector, prop){
var result = [], i,
value = (prop ? selector + "{" + prop + "}" : selector).replace(/\s/g, ''), // remove whitespaces
s = prop ? "cssText" : "selectorText";
for( i=0; i < rules.length; i++ )
if( rules[i][s].replace(/\s/g, '') == value)
result.push(i);
return result;
}
console.log( getStyleRuleIndexBySelector('.second' ) );
console.log( getStyleRuleIndexBySelector('.second', 'display:none; left:1px;') );
这篇关于通过名称获取CSS规则的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!