我正在编写一个chrome扩展名,该扩展名可操纵页面的样式表,并希望在样式表本身中存储一些额外的信息。对我来说,简单地用值创建“假”属性然后读取它们(即使用styleElem.sheet.cssRules
)是否合法?
即
.myclass {
background-color: yellow;
bogus-property: 10;
}
!
最佳答案
通常,使用自定义属性会被忽略,并且CSSStyleDeclaration无法读取。
但是,只要您使用受支持的浏览器,并且知道属性名称,就可以使用带前缀的Custom Properties:带双破折号--
前缀的属性,并打算与var() css函数一起使用。
例如:
body {
--my-property:30px;
}
要通过javascript获取此值,请访问包含的样式表的CSSStyleDeclaration,然后使用完整的属性名称调用getPropertyValue()。
var style = document.styleSheets[0].rules[0].style;
console.log( style.getPropertyValue('--my-property') );
请注意,如果您使用的是外部链接的CSS文件,则需要在设置了属性的元素上使用window.getComputedStyle()。由于样式声明对于外部CSS不可读。
var style = window.getComputedStyle(document.body);
console.log( style.getPropertyValue('--my-property') );
演示版
var style = document.styleSheets[0].rules[0].style;
console.log( style.getPropertyValue('--custom-property') );
console.log( style.getPropertyValue('--other-property') );
body {
--custom-property:30px;
--other-property:url('some.jpg');
font-size:var(--custom-property);
}
Custom properties should be printed in console log of supporting browsers