如何在 IE9 剥离之前获取样式属性值

How to get style attribute value before IE9 strips it

我试图在 IE9-10 去除无效值之前获取样式属性的值。到目前为止,我已经尝试了以下所有变体 -

[=11=].attributes.style [=12=].style [=13=].getAttribute('style')

但似乎如果我尝试设置无效值,我将无法访问它 -

<div style="display: none; color: ${fake-value}">

</div>

以上所有只会 return display: none 因为 IE9-10 会删除无效值。

请注意,我已经尝试了很多变体,所以如果不可能,那也没关系,但是你试过了吗或者你能试试吗 答案没有多大帮助,除非他们被确认做某事:)

您不能在您的元素上使用自定义属性来保存 "invalid" 数据吗?喜欢 <element data-custom-attribute="some invalid stuff"></element>.

然后也许使用 Javascript 你可以使用它并将它添加到样式中。

这是完全开箱即用的,但如果您只需要阅读 属性,为什么不使用 outerHTML 并从那里获取值,例如:

var a = document.getElementById('myDiv').outerHTML;
var i = a.search('color:');
var e = a.lastIndexOf('"');
var result = a.substr(i+6,e - (i+6));
alert(result);

编辑 1: 由于之前的答案没有用,我尝试了一些其他的选择,并且我能够向 style 标签添加一些东西并且实际上保留它的唯一方法是:

style="display:none; -ms-custom: test;"

编辑 2 如果您需要添加一个未被 IE 删除的自定义样式,您可以在它之前添加 -ms-,只有 IE 会读取它,因为它是 -ms 所以它是安全的

嗯...我认为您需要对该元素使用 ng-style。 Ng-style 将以不同的方式进行评估,然后用适当的值填充元素的样式。通常你将 agular 评估元素放在它们相应的 angular 指令中。在你的情况下,这是 ng 风格。

例如 <element style="properStyle" ng-style="scopeVariableContainingMoreStyle"></element> 将添加您的正确样式,然后添加评估的样式。

不幸的是,由于 IE9 实现 CSS 对象模型规范的方式,这是不可能的。

如果我们看一下规范,我们可以假设会发生以下情况(强调我的):

6.7.1 Parsing CSS Values

To parse a CSS value value for a given property means to follow these steps:

  • Let list be the value returned by invoking parse a list of component values from value.

  • Match list against the grammar for the property property in the CSS specification.

  • If the above step failed, return null.

  • Return list.

由于您的自定义颜色值与颜色 属性 的语法不匹配,IE returns null,基本上忽略了解析时的 属性,在它之前显示在 DOM.


虽然你提到你不想,但我再次建议你使用数据属性来代替,这将为你提供一个跨平台的解决方案:

<div style="display: none;" data-color="${fake-value}">

如果您真的无法使用数据属性,还有一种选择是通过编程方式查看页面的源代码,然后将其解析为您指定的值。我不推荐这个,但如果这是你想探索的途径,你可以找到一个相关的问题 here


更新:

有趣的是,如果我们查看 CSS Style Declarations 的 DOM 规范,我们会发现:

While an implementation may not recognize all CSS properties within a CSS declaration block, it is expected to provide access to all specified properties in the style sheet through the CSSStyleDeclaration interface

因此,作为对我之前回答的更新,我推测 IE9 在 DOM 解析,而不是预期的 DOM 实现。

这解释了为什么您在其他浏览器中获得了预期的结果。