2010-07-13 177 views
2

style属性设置为元素在IE 6/7中不起作用。但在其他浏览器中,它运行良好。setAttribute风格在IE中不起作用

我使用的代码是

var box_style = 'width: 200px; background:red'; 

document.getElementById('box').setAttribute("style", box_style); 

这适用于所有其他的浏览器IE除外6/7

难道我做错了什么?或者是否有解决这个问题的方法?请帮忙 !

回答

3

尝试改变,要

var box = document.getElementById('box'); 
box.style.width = '200px'; 
box.style.backgroundColor = 'red'; 
+1

如何设置'-webkit-border-radius'和其他css3属性? – 2010-07-13 13:04:31

+0

一般规则:删除连字符并大写以下字母:'background-color'变为'backgroundColor','-webkit-border-radius'变成'WebkitBorderRadius'。 – RoToRa 2010-07-13 13:19:35

+1

实际上'-webkit'在这里是个例外。它应该是'WebkitBorderRadius',就像它是'MozBorderRadius',但实际上它是'webkitBorderRadius'。 – bobince 2010-07-13 13:24:16

3

Internet Explorer 6-7的setAttribute/getAttribute的实现失效。不要使用它们。

从本质上讲,的setAttribute(IE浏览器)看起来是这样的:

function (attribute, value) { 
    this[attribute] = value; 
} 

因此,如果没有一个1:属性名和属性名之间的一对一关系,它打破。

单独设置您的属性,或者,这通常更好,请设置className并在外部样式表中定义样式。

+1

1。除非每个元素真的是唯一的样式,'className' + stylesheet通常是一个更干净的方法。 – bobince 2010-07-13 13:28:29

-1

另外,您可以使用PrototypeJS框架(http://www.prototypejs.org),它可以让你做到以下几点:

$('box').setStyle({ 
    width: '200px', 
    backgroundColor : 'red' 
}); 
+4

以什么方式优于'box.style.width = ...;'? – bobince 2010-07-13 13:25:38

+0

嗯,这是一个替代方案,并不是非常出众。但为了克服一些跨浏览器问题,使用像PrototypeJS,jQuery,MooTools这样的框架通常是一个好主意。 – Javaguru 2010-07-13 14:20:27

11

最终的答案cssText

el.style.cssText = 'width: 200px; background:red'; 

备注

避免在任何地方设置/ getAttribute!

+0

感谢galambalazs ....它救了我的生命时间 – 2013-02-27 13:26:36

+0

这对我的作品。和跨浏览器(甚至IE6) – 2013-04-11 08:46:16

0

可以使用的setAttribute即也兼容IE-8和IE-7

var el = document.getElementById('id' + id); 
el.setAttribute('fontWeight','bold'); 
el.setAttribute('color','red'); 
el.setAttribute('fontSize','150%'); 
el.setAttribute('bgColor','red'); 

用于向元件分配一个类的话,建议下列

el.className = "class-name";