如何在严格模式下设置元素样式属性? [英] How to set element style property in strict mode?

查看:80
本文介绍了如何在严格模式下设置元素样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于:

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);

我看到 TypeError:尝试分配给readonly属性。 iframe.style = 行上的$ c>。

I see TypeError: Attempted to assign to readonly property. on the iframe.style = line when testing in Safari, using strict mode.

虽然可能有理由要求 .style 的setter或类似的东西,我似乎无法找到有关此要求的任何信息,我也无法找到推荐我应该做的事情。

While it might make sense to require a setter or similar for .style, I can't seem to find any information about this being a requirement, and I can also can't find a recommendation for what I should be doing instead.

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

Some searching lead me to CSSStyleDeclaration.setProperty(), which may be what I want, but I'm not sure. And even if that's the right thing to do, I still haven't found any information on either which browsers support this; or how to make sure it works both with/without strict mode and in new/old browsers.

推荐答案

如果你正在服用方法,您需要编辑 element.style.cssText 而不是 element.style

If you are taking that approach, you need to edit element.style.cssText not element.style.

来自 Mozillas文档


无法通过为(只读)样式属性指定字符串来设置样式,如elt.style =color:blue ;。这是因为style属性返回一个CSSStyleDeclaration对象。

Styles can not be set by assigning a string to the (read only) style property, as in elt.style = "color: blue;". This is because the style attribute returns a CSSStyleDeclaration object.

请注意,覆盖它会覆盖元素上所有现有的内联样式,所以你通常想要设置 element.style.display =none;

Note that overwriting it will overwrite all the existing inline styles on the element, so you'll generally want to set element.style.display = "none"; instead.

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

A better approach, generally, is to modify the classes to which the element belongs and have your styles defined in a separate stylesheet.

这篇关于如何在严格模式下设置元素样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆