新建2.html,编写代码,实现点击按钮改变div背景颜色效果,颜色为随机产生的。
时间: 2024-04-30 20:19:05 浏览: 14
请参考以下代码实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>随机改变背景颜色</title>
<style>
#color-div {
width: 200px;
height: 200px;
background-color: #ccc;
margin: 20px auto;
}
button {
display: block;
margin: 20px auto;
padding: 10px;
font-size: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="color-div"></div>
<button onclick="changeColor()">点击我改变背景颜色</button>
<script>
function changeColor() {
// 生成随机颜色
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var color = "rgb(" + r + "," + g + "," + b + ")";
// 改变背景颜色
document.getElementById("color-div").style.backgroundColor = color;
}
</script>
</body>
</html>
```
在浏览器中打开该 HTML 文件,点击按钮即可随机改变 div 的背景颜色。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)