【问题标题】:Uncaught TypeError: Cannot set property style of #<HTMLElement> which has only a getter未捕获的类型错误:无法设置只有 getter 的 #<HTMLElement> 的属性样式
【发布时间】:2016-02-03 03:24:54
【问题描述】:

以下代码在 Chrome、Safari 中失败,在 Firefox 中运行良好

"use strict";
document.body.style = "background-color: green;";
&lt;p&gt;background should be green&lt;/p&gt;

去掉“using strict”就可以了。

这是 Chrome 和 Safari 中的错误还是 Firefox 中的错误? MDN says setting the style is valid

【问题讨论】:

  • 仔细阅读。 styles can not be set by assigning a string to the (read only) style property
  • 该代码适用于 Chromium 50(可能之前)。

标签: javascript google-chrome


【解决方案1】:

问题

并非所有浏览器都支持将包含 CSS 声明块的文本表示的字符串分配给 style 属性。

element.style = styleString; // Might not work

解决方法

作为一种解决方法,您可以将其设置为内容属性,或设置为cssText 属性:

element.setAttribute('style', styleString);
element.style.cssText = styleString;

标准行为

在兼容 DOM L2 样式和 ES5 的旧浏览器上,分配应该

  • 在严格模式下抛出
  • 在非严格模式下被忽略。

在兼容 CSSOM 和 ES5 的较新浏览器上,分配应该

  • 始终工作

详细信息

根据DOM Level 2 Style规范,style属性在ElementCSSInlineStyle接口中定义如下:

interface ElementCSSInlineStyle {
  readonly attribute CSSStyleDeclaration  style;
};

因此,style 属性应实现为带有 getter 但不带 setter 的 accessor property

Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'style'); /* {
  configurable: true,
  enumerable: true,
  get: function(){...},
  set: undefined
} */

根据ECMAScript 5,当您尝试为这样的属性分配一些值时,必须在严格模式下抛出错误:

当在strict mode code 中发生分配时,[...] LeftHandSide 也可能不是对具有属性值 {[[Set]]:undefined} [...] 的访问器属性的引用 [...]。在 在这些情况下会抛出 TypeError 异常。

不过,DOM L2 样式已被较新的 CSS 对象模型 (CSSOM) 取代。

根据该规范,由HTMLElement 实现的接口ElementCSSInlineStylestyle IDL 属性定义为[PutForwards] 扩展属性:

[NoInterfaceObject]
interface ElementCSSInlineStyle {
  [SameObject, PutForwards=@987654329@] readonly attribute @987654330@ @987654331@;
};

这意味着设置style 属性的行为必须类似于设置cssText 之一CSSStyleDeclaration。因此,它们必须是等价的:

element.style = styleString;
element.style.cssText = styleString;

这就是为什么它适用于较新的浏览器。

【讨论】:

  • 这不是问题的答案。不寻找解决方法
  • @gman 好的,我已经包含了解释。如果您只想知道哪种实现是正确的而不是解决方法,我建议您使用[language-lawyer] 标记您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多