且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

setAttribute 不适用于 IE 上的“样式"属性

更新时间:2023-12-05 14:22:22

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

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.