setAttribute 不适用于 IE 上的“样式"属性 [英] setAttribute is not working for 'style' attribute on IE

查看:18
本文介绍了setAttribute 不适用于 IE 上的“样式"属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一段为 Firefox 编写的 JS 代码移植到 Internet Explorer 中.我遇到了使用 Firefox 上的 setAttribute 方法更改元素样式的问题.

I'm porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttribute method which was working on Firefox.

button.setAttribute('style', 'float: right;');

我尝试设置按钮的样式成员,但也没有用.这是设置 onclick 事件处理程序的解决方案.

I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclick event handler.

button.style = 'float: right;';

首先我想知道上述问题的解决方案和
其次,是否有针对浏览器之间这些差异的维护列表?

First I wanna know the solution for the above problem and
Second are there any maintained lists for these differences between browsers ?

推荐答案

因为样式本身就是一个对象.你想要的是:

Because style itself is an object. What you want is:

button.style.setAttribute('cssFloat','right');

但是 IE 不支持样式对象的 setAttribute.所以使用完全支持的跨浏览器:

But IE doesn't support setAttribute for style objects. So use the fully cross-browser supported:

button.style.cssFloat = 'right';

作为参考,我总是去 www.quirksmode.org .具体来说:http://www.quirksmode.org/compatibility.html.点击所有与 DOM 相关的内容.

As for reference, I always go to www.quirksmode.org . Specifically: http://www.quirksmode.org/compatibility.html . Click on all the DOM related stuff.

最后,要设置多个属性,我通常使用以下内容:

And finally, to set multiple attributes I usually use something like:

function setStyle(el,spec) {
    for (var n in spec) {
        el.style[n] = spec[n];
    }
}

用法:

setStyle(button,{
    cssFloat : 'right',
    border : '2px solid black'
});

注意:object.attribute = 'value' 虽然适用于所有浏览器,但可能并不总是适用于非 HTML DOM 对象.例如,如果您的文档包含需要使用 javascript 操作的嵌入式 SVG 图形,则需要使用 setAttribute 来完成.

Note: object.attribute = 'value' although works in all browsers may not always work for non-HTML DOM objects. For example, if your document contains embedded SVG graphics that you need to manipulate with javascript you need to use setAttribute to do it.

这篇关于setAttribute 不适用于 IE 上的“样式"属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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