Version: Next
控制样式
方式一
使用元素的Style属性,按照css字段设置
div1.style.border = "1px solid red";
方式二
提前定义好类选择器的样式,通过元素的className属性来设置其class属性值,套用CSS类选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>控制元素样式</title>
<style>
.d1 {
border: 1px solid red;
width: 100px;
height: 100px;
}
.d2 {
border: 1px solid blue;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="div1">
divdivdiv
</div>
<hr/>
<div id="div2">
divdivdiv
</div>
<hr/>
<script>
//获取div1
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div1.onclick = function () {
//修改样式方式1
div1.style.border = '1px dashed red';
div1.style.width = '200px';
div1.style.fontSize = '20px';
}
div2.onclick = function () {
//方式2,作用样式,设置属性值class=xxx
div2.className = 'd1';
}
</script>
</body>
</html>