Set CSS property in Javascript?

2019-01-02 15:53发布

I've created the following...

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

How would I now set CSS attributes e.g width: 100px?

11条回答
浅入江南
2楼-- · 2019-01-02 16:13

That's actually quite simple with vanilla JavaScript:

menu.style.width = "100px";
查看更多
怪性笑人.
3楼-- · 2019-01-02 16:16
<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'"/>
查看更多
旧时光的记忆
4楼-- · 2019-01-02 16:20

Use element.style:

var element = document.createElement('select');
element.style.width = "100px";
查看更多
人间绝色
5楼-- · 2019-01-02 16:24

All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.

Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.

In prototype I would do:

$(newElement).addClassName('blah')
查看更多
与君花间醉酒
6楼-- · 2019-01-02 16:25
<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>
查看更多
只若初见
7楼-- · 2019-01-02 16:27

Just for people who want to doing the same thing in 2018

You can assign a CSS custom property to your element (through CSS or JS) and change it:

Assigment through CSS:

element {
  --element-width: 300px;

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

Assignment through JS

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

Get property value through JS

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

Here useful links:

查看更多
登录 后发表回答