Setting the style
attribute to elements is not working in IE 6/7 . But in other browsers, it works well.
The code i am using is
var box_style = 'width: 200px; background:red';
document.getElementById('box').setAttribute("style", box_style);
This works in all other browsers except 开发者_Go百科IE 6/7
Am i doing anything wrong ? or is there any solution for this problem ? Please help !
The ultimate answer is cssText
:
el.style.cssText = 'width: 200px; background:red';
The side note is
Avoid set/getAttribute everywhere you can!
Try changing that to
var box = document.getElementById('box');
box.style.width = '200px';
box.style.backgroundColor = 'red';
Internet Explorer 6-7 has a broken implementation of setAttribute / getAttribute. Don't use them.
Essentially, setAttribute (for IE) looks something like this:
function (attribute, value) {
this[attribute] = value;
}
So if there isn't a 1:1 relationship between the property name and the attribute name, it breaks.
Set your properties individually, or, and this is generally better, set className and define the styles in an external stylesheet.
you can use setAttribute that is also compatible with IE-8 and IE-7
var el = document.getElementById('id' + id);
el.setAttribute('fontWeight','bold');
el.setAttribute('color','red');
el.setAttribute('fontSize','150%');
el.setAttribute('bgColor','red');
for assigning a class to an element, i suggest following
el.className = "class-name";
Alternatively you could use PrototypeJS framework (http://www.prototypejs.org), which allows you to do the following:
$('box').setStyle({
width: '200px',
backgroundColor : 'red'
});
精彩评论