<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态改变css样式</title>
<style>
*{margin: 0;padding: 0;}
div{
margin:0 auto;
width: 500px;
height: 300px;
line-height: 300px;
text-align: center;
}
.blue{
background-color: blue;
}
.red{
background-color: red;
}
button{
width: 100px;
}
</style>
</head>
<body>
<div class="red">
<button onclick="hello()">改变背景颜色</button>
<!--<button onclick="javascript:alert('hello')">改变背景颜色</button>-->
<!--<a href="javascript:alert('hello')">改变背景颜色</a>-->
</div>
</body>
<script>
let divs=document.getElementsByTagName('div')
function hello(){
//找到需要改变背景颜色的容器
if(divs[0].className='red'){
divs[0].className='blue'
}else{
divs[0].className='red'
}
}
</script>
</html>
![image-20260707084502579]()