使用JavaScript添加多种样式

Add Multiple Styles with JavaScript

本文关键字:样式 添加 JavaScript 使用      更新时间:2023-09-26

我想用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

一次又一次。提前感谢!

document.getElementById("id1").setAttribute(
  "style", "color: green; background-color: beige; padding-bottom: 2px; margin: 3px;");
<body>
  <h1 id="id1">My Heading 1</h1>
  <button type="button" onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>

这是一把小提琴。

是的,您可以使用类似的JavaScript添加多个CSS

你的按钮

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

以及的JavaScript

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

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

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

如果您的样式是动态生成的,并且您不能简单地向该元素添加一个新的CSS类,那么您可以使用与发布的想法相同的想法,但以DRY的方式进行编码。

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

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

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];
}
<div id="content">
  This is a test
</div>

document.getElementById('the_object_ID')
  .setAttribute( 'style', 'color:white; margin:20px;');

您可以为所有这些创建一个函数

<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";
}

最简单的答案是使用。样式如下:

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