setAttribute样式在IE中不起作用

时间:2010-07-13 12:49:17

标签: javascript internet-explorer dom

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

我正在使用的代码是

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

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

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

我做错了吗?或者有没有解决这个问题的方法?请帮忙!

5 个答案:

答案 0 :(得分:12)

最终答案cssText

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

旁注

  

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

答案 1 :(得分:5)

尝试将其更改为

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

答案 2 :(得分:3)

Internet Explorer 6-7的setAttribute / getAttribute实现方式已损坏。不要使用它们。

基本上,setAttribute(对于IE)看起来像这样:

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

因此,如果属性名称和属性名称之间没有1:1关系,则会中断。

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

答案 3 :(得分:0)

您可以使用与IE-8和IE-7兼容的setAttribute

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

答案 4 :(得分:-1)

或者您可以使用PrototypeJS框架(http://www.prototypejs.org),它允许您执行以下操作:

$('box').setStyle({
  width: '200px',
  backgroundColor : 'red'
});
相关问题