使用Javascript / JQuery获取类或id的所有CSS属性
是否可以指定类或ID并获取该特定类或ID的所有CSS规则。我不是指一个元素,我想指定一个类并返回该类的所有CSS。
Is it possible to specify a class or an ID and get all the CSS rules for that particular class or ID. I don't mean an element, I want to specify a class and return all CSS for that class.
我知道我可以使用 .style
来获取内联样式,但我不需要内联,它必须来自样式表。
I know I can use .style
to get inline styles but I don't need inline, it has to come from the stylesheet.
JS甚至可以实现吗?它可以访问.css文件并返回某个类的属性列表吗?
Is it even possible with JS? Can it access the .css file and return a list of properties for a certain class?
没有代码的道歉,这更像是一个理论问题,尽管如果有人有一个函数在手边,我很乐意研究它。
Apologies for no code, it's more of a theoretical question although if someone has a function at hand, I'd be happy to study it.
使用 document#styleSheets 并将所有样式表中的所有规则提取到数组中。然后通过 selectorText
过滤数组。
Use document#styleSheets and extract all rules from all stylesheets into array. Then filter the array by the selectorText
.
注意:我使用了一个简单的数组#include来检查请求的选择器是否出现在 selectorText
,但您可能想要创建更严格的检查以防止误报。例如,选择器文本 .demo
也可以找到 .demogorgon
的规则。
Note: I've used a simple Array#includes to check if the requested selector appears in selectorText
, but you might want to create a stricter check to prevent false positives. For example the selector text .demo
can find rules for .demogorgon
as well.
const findClassRules = (selector, stylesheet) => {
// combine all rules from all stylesheets to a single array
const allRules = stylesheet !== undefined ?
Array.from((document.styleSheets[stylesheet] || {}).cssRules || [])
:
[].concat(...Array.from(document.styleSheets).map(({ cssRules }) => Array.from(cssRules)));
// filter the rules by their selectorText
return allRules.filter(({ selectorText }) => selectorText && selectorText.includes(selector));
};
console.log(findClassRules('.demo', 0));
.demo {
color: red;
}
.demo::before {
content: 'cats';
}