我已经创建了以下…
var menu = document.createElement('select');
我现在如何设置CSS属性,如宽度:100px?
我已经创建了以下…
var menu = document.createElement('select');
我现在如何设置CSS属性,如宽度: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
其他回答
这其实用JavaScript很简单:
menu.style.width = "100px";
只需设置样式:
var menu = document.createElement("select");
menu.style.width = "100px";
或者如果你喜欢,你可以使用jQuery:
$(menu).css("width", "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>
所有的答案都正确地告诉你如何做你问的事情,但我建议使用JavaScript在元素上设置一个类,并使用CSS设置它的样式。这样你就能正确区分行为和风格。
想象一下,如果你有一个设计师重新设计网站的风格……他们应该能够完全在CSS工作,而不必与你的JavaScript工作。
在原型中我会这样做:
$(newElement).addClassName('blah')
<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'"/>