setAttribute样式在IE中不起作用

Aak*_*thy 3 javascript internet-explorer dom

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

我正在使用的代码是

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

document.getElementById('box').setAttribute("style", box_style);
Run Code Online (Sandbox Code Playgroud)

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

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

gbl*_*zex 12

最终的答案cssText:

el.style.cssText = 'width: 200px; background:red';
Run Code Online (Sandbox Code Playgroud)

侧面说明

尽量避免使用set/getAttribute!


Poi*_*nty 5

尝试将其更改为

var box = document.getElementById('box');
box.style.width = '200px';
box.style.backgroundColor = 'red';
Run Code Online (Sandbox Code Playgroud)