在下拉框中选择一个颜色,然后根据选择的颜色点击按钮来更改div的背景颜色,请输出完整的html代码
时间: 2024-03-02 10:49:35 浏览: 76
当您选择颜色并单击按钮时,背景颜色将更改为您选择的颜色。
完整的HTML代码如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<title>Change Background Color</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
max-width: 800px;
padding: 2em;
text-align: center;
}
#myDiv {
background-color: #fff;
border: 1px solid #ccc;
height: 200px;
margin: 2em auto;
width: 200px;
}
</style>
</head>
<body>
<div class="container">
<h1>Change Background Color</h1>
<label for="colorSelect">Select a color:</label>
<select id="colorSelect">
<option value="#f00">Red</option>
<option value="#0f0">Green</option>
<option value="#00f">Blue</option>
<option value="#ff0">Yellow</option>
<option value="#f0f">Purple</option>
<option value="#00ff00">Lime</option>
<option value="#ff00ff">Fuchsia</option>
<option value="#00ffff">Aqua</option>
</select>
<button id="changeColorBtn">Change Color</button>
<div id="myDiv"></div>
</div>
<script>
const colorSelect = document.getElementById('colorSelect');
const changeColorBtn = document.getElementById('changeColorBtn');
const myDiv = document.getElementById('myDiv');
changeColorBtn.addEventListener('click', () => {
myDiv.style.backgroundColor = colorSelect.value;
});
</script>
</body>
</html>
```
阅读全文