我从 document.styleSheets
中检索了一个 CSS 规则现在正在寻找提取它的属性和值。
cssText = ".expl { position: absolute; background-color: rgb(204, 204, 204); max-width: 150px; }";
是否可以使用正则表达式来检索匹配项中的属性及其适当的值?另外,去掉尾随的分号。
我想得到如下结果:
position: absolute // match 1
background-color: rgb(204, 204, 204) // match 2
max-width: 150px // match 3
我只是到了提取括号内内容的地步:(?<={)(.*)(?=})
,不知道我应该继续做什么。
我如何实现这一目标?
提前致谢!
最佳答案
您可以在 ;
上拆分字符串
document.getElementById(id).style.cssText.split(";")
编辑:
请注意,样式对象的 cssText 属性不包含选择器
编辑 2:
好的,我做了更多的挖掘,看来您是从 CSSStyleRule 对象获取 cssText 属性的。这包括选择器。您可以通过更多的树遍历获得一个以分号分隔的实际规则列表。您可以使用
获取样式对象document.styleSheets[1].cssRules[0].style.cssText;
代替
document.styleSheets[1].cssRules[0].cssText;
查看此深入分析:
关于javascript - 匹配 CSS "<property>: <value>"的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7679214/