问题
并非所有浏览器都支持将包含 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 实现的接口ElementCSSInlineStyle 的style IDL 属性定义为[PutForwards] 扩展属性:
[NoInterfaceObject]
interface ElementCSSInlineStyle {
[SameObject, PutForwards=@987654329@] readonly attribute @987654330@ @987654331@;
};
这意味着设置style 属性的行为必须类似于设置cssText 之一CSSStyleDeclaration。因此,它们必须是等价的:
element.style = styleString;
element.style.cssText = styleString;
这就是为什么它适用于较新的浏览器。