<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>07-修改样式属性</title>
<style>
.one {
width: 50px;
height: 50px;
background-color: skyblue;
}
.two {
width: 50px;
height: 50px;
background-color: purple;
}
.change {
background-color: pink;
}
</style>
</head>
<body>
<div id="one" class="one">1</div>
<div id="two" class="two">2</div>
<script>
// 方式1
const one = document.querySelector('#one');
one.onclick = function () {
// 这种方式是直接添加到div的内联样式
this.style.backgroundColor = 'red';
}
// 方式2
const two = document.querySelector('#two');
two.addEventListener('click', function () {
// 这种方式会直接覆盖原来的class选择器
this.className = 'change';
// 如果想要保留之前的,那么可以写成:
// this.className = 'two change';
})
</script>
</body>
</html>