动态修改背景颜色

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript 网页设计案例</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
.container {
text-align: center;
padding: 20px;
border-radius: 10px;
background-color: #fff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
button {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
margin-top: 20px;
}
button:hover {
background-color: #45a049;
}
p {
font-size: 14px;
color: #555;
}
</style>
</head>
<body>
<div class="container">
<h1>欢迎来到动态网页设计</h1>
<button id="changeColorBtn">改变背景颜色</button>
<p>点击按钮改变背景颜色</p>
</div>
<script>
const button = document.getElementById('changeColorBtn');
const colors = ['#FF5733', '#33FF57', '#3357FF', '#F1C40F', '#9B59B6', '#E74C3C'];
button.addEventListener('click', () => {
const randomColor = colors[Math.floor(Math.random() * colors.length)];
document.body.style.backgroundColor = randomColor;
});
</script>
</body>
</html>