我正在尝试从样式表中将值传递给 javascript。 我已经看到我可以使用 CSSRule.cssText 获取选择的值: https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/cssText 但如果我想使用一个不被识别为 css 的属性值对,它就不会显示。
此处解决了是否可以返回非标准值的问题: Can I fetch the value of a non-standard CSS property via Javascript?
我很好奇是否有一些解决方法可以在本地将我的属性添加到接受的 css 属性列表中,以便 CSSRule.cssText 返回它?
最佳答案
如何使用伪 :before
或 :after
元素的 content
属性来传递一个字符串,然后将其解析为目的。可能不是一个优雅的方法,但似乎可行。
var stylesheet = document.styleSheets[0],
h1 = document.getElementById('foo'),
customProp;
/*
ParseData function was taken from :
http://www.bennadel.com/blog/1496-ask-ben-parsing-string-data-using-javascript-s-string-replace-method.htm
*/
function ParseData( strData ){
var objCollection = {}
strData.replace(
new RegExp( "\\[(\\w+)=([^\\]]*)\\]", "gi" ),
function( $0, $1, $2 ){
objCollection[ $1 ] = $2;
}
);
return( objCollection );
}
// you could as well target the content property directly here.
customProp = ParseData(stylesheet.cssRules[1].style.cssText);
h1.innerHTML += customProp.foo;
#foo {
color: tomato;
}
#foo:before {
content: '[foo= loves Bar!]';
display: none;
}
<h1 id="foo">Foo</h1>
关于javascript - 是否可以本地扩展 Web API 以允许 CSSRule.cssText 返回非标准 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040401/