[英]Get all CSS properties for a class or id with Javascript/JQuery
是否可以指定一个类或一个 ID 并获取该特定类或 ID 的所有 CSS 规则。 我不是指一个元素,我想指定一个类并返回该类的所有 CSS。
我知道我可以使用.style
来获取内联样式,但我不需要内联,它必须来自样式表。
甚至可以用 JS 吗? 它可以访问 .css 文件并返回某个类的属性列表吗?
抱歉没有代码,这更像是一个理论问题,尽管如果有人手头有功能,我很乐意研究它。
你可以这样做:
window.getComputedStyle($('[your class name]')[0])
查看https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle了解更多信息。
使用document#styleSheets并将所有样式表中的所有规则提取到数组中。 然后通过selectorText
过滤数组。
注意:我使用了一个简单的 Array#includes 来检查请求的选择器是否出现在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'; }
使用 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 但对于样式问题,我没有找到更快更容易的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.