我已经创建了以下…

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

我现在如何设置CSS属性,如宽度: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>

其他回答

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

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

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

var element = document.createElement('select');
element.style.maxWidth = "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"

仅供在2018年想做同样事情的人使用

你可以为你的元素指定一个CSS自定义属性(通过CSS或JS)并更改它:

通过CSS分配:

element {
  --element-width: 300px;

  width: var(--element-width, 100%);
}

通过JS赋值

ELEMENT.style.setProperty('--element-width', NEW_VALUE);

通过JS获取属性值

ELEMENT.style.getPropertyValue('--element-width');

以下是有用的链接:

https://developer.mozilla.org/en-US/docs/Web/CSS/-- * https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty

当调试时,我喜欢能够在一行中添加一堆css属性:

menu.style.cssText = 'width: 100px';

习惯了这种风格,你可以在一行中添加一堆css,像这样:

menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';