javascript - 是否可以本地扩展 Web API 以允许 CSSRule.cssText 返回非标准 css 属性

标签 javascript css mozilla

我正在尝试从样式表中将值传递给 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/

相关文章:

javascript - 检查变量是否初始化为 JavaScript 中的数字的标准方法是什么?

javascript - 对象中的项目为 'undefined' 的问题

javascript - Passport - 双人战略 "ERR|The username passed to sign_request() is invalid"

html - CSS:如何处理特定标签

jquery - 隐藏和取消隐藏相关下拉菜单

javascript - Chrome 上 msSaveOrOpenBlob 的替代品

html - Mozilla Firefox 中缺少 CC 按钮

javascript - 流畅的动画跟随光标

javascript - HTML5 和 @font-face 与 IE

google-chrome - 为什么我的 Google Adsense 广告在 Chrome 中被屏蔽(没有广告拦截器)但 Mozilla 显示它们?