开发者

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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜