如何在严格模式下设置元素样式属性?

Let*_*ion 5 javascript css

鉴于:

body = document.getElementsByTagName('body')[0];
iframe = document.createElement('iframe');
iframe.src = protocol + settings.scriptUrl + a;
iframe.height = 1;
iframe.width = 1;
iframe.scrolling = 'no';
iframe.frameborder = 0;
iframe.style = 'display:none';
body.appendChild(iframe);
Run Code Online (Sandbox Code Playgroud)

我在使用严格模式在Safari中测试时看到TypeError: Attempted to assign to readonly property.了这一点iframe.style =.

虽然可能需要一个setter或类似的东西.style,我似乎无法找到任何关于这是一个要求的信息,我也无法找到我应该做什么的建议.

一些搜索引导我到CSSStyleDeclaration.setProperty(),这可能是我想要的,但我不确定.即使这是正确的事情,我仍然没有找到关于哪个浏览器支持这个的任何信息; 或者如何确保它在有/没有严格模式和新/旧浏览器中都有效.

Que*_*tin 14

如果你正在服用这种方法,你需要编辑element.style.cssText没有element.style.

来自Mozillas的文档:

无法通过将字符串分配给(只读)样式属性来设置样式,如elt.style ="color:blue;".这是因为style属性返回CSSStyleDeclaration对象.

请注意,覆盖它将覆盖元素上的所有现有内联样式,因此通常需要设置element.style.display = "none";.

通常,更好的方法是修改元素所属的类,并在单独的样式表中定义样式.