2015-03-03 130 views
1

的对象设置element.style有没有办法做这样的事情:的与样式属性


    var my_element= document.createElement("div"); 
    my_element.style={ 
     position:"absolute", 
     background:"red", 
     ... 
    } 

代替:

my_element.style.position= "absolute"; 
my_element.style.background= "red"; 

或者

var my_properties={ 
     position:"absolute", 
     background:"red", 
     ... 
} 
for(var i in my_properties) 
    my_element.style[i]= my_properties[i]; 
+0

第2个选项应该工作 – Satpal 2015-03-03 08:02:52

+0

我知道了!其实,我在写这个问题的时候想到了这个问题。我仍然要求在这种情况下存在更好的解决方案 – Gael 2015-03-03 08:04:45

回答

0

待办事项它使用for...in

var my_element= document.createElement("div"); 
var elemStyle = my_element.style; 
var my_properties={ 
     position:"absolute", 
     background:"red", 
     ... 
} 
for(var prop in my_properties) { 
    elemStyle[prop] = my_properties[prop]; 
} 

或者你可以setAttribute为风格。

var elemstyle = my_element.getAttribute("style"); 
my_element.setAttribute(
    "style", elemstyle+"font-size: 100px; font-style: italic; color:#ff0000;"); 
+0

对于第二种,它会覆盖元素的现有样式,但正如我刚刚创建的那样,它对我很有用 – Gael 2015-03-03 08:06:58

+0

@Gael,yupe,请参阅更新后的答案。 – void 2015-03-03 08:10:46

+0

字体大小之前的分号会更安全。我尝试编辑你的答案,但我只有一个修改... – Gael 2015-03-03 08:15:01