Applying styles in javascript with a for-in loop
So I have an object full of key-value 开发者_运维知识库pairs that describe the intended style of an element and I am trying to apply that style to an element by looping through the object like this:
element = document.createElement('div');
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
element.style.x = style[x];
}
And yet the element remains without a style. This seems so simple that I cannot figure out what might be going wrong,so I assume I am missing something incredibly obvious. Thank you for any help you can provide.
You are setting the property x
on each iteration. Instead, use the value of x
like so:
element.style[x] = style[x];
Change to this:
element = document.createElement('div');
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
element.style[x] = style[x];
}
精彩评论