简体   繁体   English

使用for-in循环在javascript中应用样式

[英]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. 您将在每次迭代中设置属性x Instead, use the value of x like so: 而是使用x的值,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM