【问题标题】:Is the 'getPropertyValue' method required for retrieving CSS?检索 CSS 是否需要“getPropertyValue”方法?
【发布时间】:2015-10-08 23:30:53
【问题描述】:

如果我们只能使用getComputedStyle 方法,你能告诉我为什么我们需要使用getPropertyValue 方法吗?

例如,据我了解,这将起作用:

var s = getComputedStyle(element, null).opacity;

相当于如下:

var s = getComputedStyle(element, null).getPropertyValue('opacity');

我们可以在没有getPropertyValue 的情况下使用getComputedStyle 吗?

【问题讨论】:

  • getComputedStyle 的第二个参数也不再需要了。

标签: javascript css cssom


【解决方案1】:

根据旧的DOM L2 Style,不需要getPropertyValue

CSS2Properties 接口代表了一种便利机制 在CSSStyleDeclaration 中检索和设置属性。 这个接口的属性对应所有的properties specified in CSS2。获取此接口的属性是 相当于调用getPropertyValue的方法 CSSStyleDeclaration 接口。设置 this 的属性 接口相当于调用setProperty的方法 CSSStyleDeclaration接口。

但是,不需要实现来支持它,因此使用getPropertyValue 更安全。

CSS 模块的一致实现不需要 实现CSS2Properties接口。

但根据较新的CSSOM,使用没有getPropertyValue 的驼峰式大小写必须有效:

对于每个 supported CSS property 的 CSS 属性 property, 以下部分接口适用于 camel-cased 属性 所在的位置 通过运行CSS property to IDL attribute 算法获得 属性

partial interface CSSStyleDeclaration {
    attribute DOMString _camel-cased attribute;
};

camel-cased attribute 属性在获取时必须返回 以参数为参数调用 getPropertyValue() 的结果 运行IDL attribute to CSS property 算法的结果 驼峰式属性

设置camel-cased attribute 属性必须调用 setProperty() 第一个参数是 运行IDL attribute to CSS property 算法 驼峰式属性,作为给定值的第二个参数,没有第三个参数。抛出的任何异常都必须重新抛出。

因此,getPropertyValue 不再需要检索 CSS 值。

【讨论】:

  • 感谢 Oriol 的详细回答。你已经消除了我对这个主题的所有疑虑。亲切的问候,菲利普。
【解决方案2】:

我相信它适用于不能用点表示的属性,例如background-position。虽然我想这会带来一个问题“为什么不使用括号表示法,即getComputedStyle(element, null)['background-position']?”。他们可能只是想要一个类的 getter 方法(CSSStyleDeclaration)。

【讨论】:

  • 你不能用.backgroundPosition吗?
  • 糟糕,忘记了。我自己不会使用它,因为它不可推广。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2011-01-05
  • 1970-01-01
  • 2020-10-26
  • 2021-11-06
  • 1970-01-01
相关资源
最近更新 更多