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

问题描述

我将一段为Firefox编写的JS代码移植到Internet Explorer中。我遇到了一个使用 setAttribute 方法改变元素样式的问题。这个方法在Firefox上工作。

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

我尝试设置按钮的样式成员,但它也不起作用。这是设置 onclick 事件处理程序的解决方案。

 按钮.style ='float:right;'; 

首先,我想知道上述问题的解决方案,以及

Second are there任何维护的浏览器之间的差异列表?

解决方案

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

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

但IE不支持样式对象的setAttribute。因此,请使用完全跨浏览器的支持:

  button.style.cssFloat ='right'; 

至于参考,我总是去www.quirksmode.org。具体来说:。点击所有与DOM有关的东西。
$ b

最后,为了设置多个属性,我通常使用如下所示:

 函数setStyle(el,spec){
(spec中的var n){
el.style [n] = spec [n];


$ / code $ / pre
$ b $ p用法:

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

注意: object.attribute ='value'虽然所有浏览器中的作品可能并不总是适用于非HTML DOM对象。例如,如果您的文档包含需要使用JavaScript处理的嵌入式SVG图形,则需要使用 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;');

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

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

button.style.cssFloat = 'right';

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];
    }
}

usage:

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

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.

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

08-01 17:08