是否可以指定类或ID并获取该特定类或ID的所有CSS规则。我不是指一个元素,我想指定一个类并返回该类的所有CSS。
我知道我可以使用.style
来获取内联样式,但我不需要内联,它必须来自样式表。
甚至可以使用JS吗?它可以访问.css文件并返回某个类的属性列表吗?
没有代码的道歉,它更像是一个理论问题,尽管如果有人手头有一个功能,我很乐意研究它。
答案 0 :(得分:1)
你可以这样做:
window.getComputedStyle($('[your class name]')[0])
查看https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle了解详情。
答案 1 :(得分:1)
使用document#styleSheets并将所有样式表中的所有规则提取到数组中。然后按selectorText
过滤数组。
注意:我使用了一个简单的数组#include来检查请求的选择器是否出现在selectorText
中,但您可能想要创建更严格的检查以防止误报。例如,选择器文本.demo
也可以找到.demogorgon
的规则。
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';
}

答案 2 :(得分:0)
使用jquery:
$(your element Id or class ).attr('style')
它将返回所有CSS属性
left: 75px; top: -59px; transform: rotate(0deg) scaleX(2.32432) scaleY(3.83333);
如果您只需要一个或多个(您知道需要哪种道具)
$(your element Id or class).css([
"width", "height", "fontSize", "fontFamily", 'textAlign', 'fontWeight',
'fontStyle','textDecoration','letterSpacing', 'lineHeight'])
我正在使用react并尝试避免使用jquery,但是对于样式问题,我发现并没有变得更快,更容易