我已经创建了以下…

var menu = document.createElement('select');

我现在如何设置CSS属性,如宽度:100px?


当前回答

使用element.style:

var element = document.createElement('select');
element.style.width = "100px";

其他回答

对于大多数样式,这样做:

var obj = document.createElement('select');
obj.style.width= "100px";

对于名称中有连字符的样式,这样做:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"
<body>
  <h1 id="h1">Silence and Smile</h1><br />
  <h3 id="h3">Silence and Smile</h3>

  <script type="text/javascript">
    document.getElementById("h1").style.color = "Red";
    document.getElementById("h1").style.background = "Green";
    document.getElementById("h3").style.fontSize = "larger" ; 
    document.getElementById("h3").style.fontFamily = "Arial";
  </script>
</body>
<h1>Silence and Smile</h1>
<input  type="button"  value="Show Red"   onclick="document.getElementById('h1').style.color='Red'"/>
<input  type="button"  value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>

所有的答案都正确地告诉你如何做你问的事情,但我建议使用JavaScript在元素上设置一个类,并使用CSS设置它的样式。这样你就能正确区分行为和风格。

想象一下,如果你有一个设计师重新设计网站的风格……他们应该能够完全在CSS工作,而不必与你的JavaScript工作。

在原型中我会这样做:

$(newElement).addClassName('blah')

这适用于大多数CSS属性,如果他们没有连字符。

var element = document.createElement('select');
element.style.width = "100px";

对于带有连字符的属性,如max-width,您应该将香肠大小写转换为骆驼大小写

var element = document.createElement('select');
element.style.maxWidth = "100px";