开发者

Applying styles in javascript with a for-in loop

开发者 https://www.devze.com 2023-03-30 01:42 出处:网络
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:

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

精彩评论

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