是否有可能本地扩展web API以允许CSSRule.cssText返回非标准css属性

Is it possible to locally extend web API to allow CSSRule.cssText to return a non standard css attribute

本文关键字:cssText CSSRule 返回 非标准 属性 css 有可能 扩展 API web 是否      更新时间:2023-09-26

我正在尝试从样式表中传递一个值给javascript。我已经看到,我可以使用CSSRule.cssText获得选择的值:https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/cssText但是如果我想使用不被识别为css的属性值对,它不会显示

是否可以返回非标准值的问题在这里得到了解决:我可以通过Javascript获取非标准CSS属性的值吗?

我很好奇,如果有可能有一些解决办法,我可以在本地添加我的属性到接受的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>