常见CSS操作示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>document</title>
<style>
.box{
width: 100px;
height: 100px;
}
.box1{
background-color: rebeccapurple;
}
</style>
</head>
<body id="body">
<div id="div" class="box">
<span id="span1">span1</span>
<span id="span2">span2</span>
<span id="span3">span3</span>
</div>
<script>
var div = document.getElementById("div");
//className方式设置样式
div.className = "box box1";
//classList方式操作样式
div.classList.add("box2"); //添加box2样式
div.classList.remove("box2"); //移除box2样式
console.log(div.classList.contains("box")); //返回是否包含box样式
div.classList.toggle("box2"); //有就移除,没有就添加
console.log(div);
//setAttribute方式设置样式
var span1 = document.getElementById("span1");
span1.setAttribute('style','background-color:blue;' + 'boder:1px solid red;' + 'font-size:22px');
//style方式设置样式
var span2 = document.getElementById("span2");
span2.style.backgroundColor = 'red';
span2.style.border = '1px solid black';
span2.style.fontSize = '22px';
//style.cssText方式设置样式
var span3 = document.getElementById("span3");
span3.style.cssText = "background-color:yellow;" + "boder:1px solid red;" + "font-size:22px";
</script>
</body>
</html>
1、CSSStyleDeclaration 对象属性
2、CSSStyleDeclaration 对象方法