使用JavaScript添加多个样式

时间:2016-03-28 12:52:59

标签: javascript html css

我想用JavaScript添加多行CSS。我知道我可以这样做:

document.getElementById(id).style.property=new style

如:

<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button" 
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>

但是,上面的代码只允许我添加一个CSS属性。如果想要添加多个属性,请执行以下操作:

#id1 {
    color: red;
    background-color: beige;
    padding-bottom: 2px;
    margin: 3px;
}

如何通过不重复添加所有这些:

document.getElementById(id).style.property=new style
......一次又一次。提前谢谢!

7 个答案:

答案 0 :(得分:13)

这是一个小提琴。

&#xA;&#xA;
 < code> document.getElementById(“id1”)。setAttribute(&#xA;“style”,“color:red; background-color:beige; padding-bottom:2px; margin:3px;”);&#xA; < /代码> 
&#XA;

答案 1 :(得分:4)

是的,您可以使用javascript添加多个css

你的按钮

<input id="myButton" type="button" value="Hello">

和它的javascript

document.getElementById('myButton').style.cssText = "color: blue; widht: 100px; height: 55px; border: 1px solid red;";

答案 2 :(得分:1)

为什么不添加一个已经定义了所有属性的类?

document.getElementById(id).classList.add('new_class')

答案 3 :(得分:0)

如果您的样式是动态生成的,并且您无法简单地向此元素添加新的CSS类,那么您可以执行类似的操作,使用您发布但在{{方式。

如果您的元素已经应用了某些样式并且您不想覆盖它们,这也很有用。

点击下面的运行代码段以查看演示。

&#13;
&#13;
DRY
&#13;
var id  = "content";

var styles = { 
  'color': 'red',
  'background-color': 'beige',
  'padding-bottom': '2px',
  'margin': '3px'
};

var elementStyle = document.getElementById(id).style;
for(var styleName in styles) {
  elementStyle[styleName] = styles[styleName];
}
&#13;
&#13;
&#13;

答案 4 :(得分:0)

document.getElementById(&#39; the_object_ID&#39;)。setAttribute(&#39; style&#39;,&#39; color:white; margin:20px;&#39;);

答案 5 :(得分:0)

您可以为所有这些

创建一个功能
<button type="button" onclick="myFunc('id1')"> Click Me! </button>

在js

function myFunc(id){
    var myDiv = document.getElementById(id);
    myDiv.style.color = 'red';
    myDiv.style.backgroundColor = "beige"; 
    myDiv.style.paddingBottom = "2px";
    myDiv.style.margin = "3px";
}

答案 6 :(得分:0)

最简单的答案是使用 .style 这样的:

document.getElementById("id1").style = "height:30px; width:30px; background-color:red;"