推荐答案
// www.javascriptcn.com code example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Color Picker</title>
<style>
.color-picker {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
.color-preview {
width: 100px;
height: 100px;
border: 1px solid #000;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="color-picker">
<div class="color-preview" id="colorPreview"></div>
<input type="color" id="colorInput" value="#ff0000">
</div>
<script>
const colorInput = document.getElementById('colorInput');
const colorPreview = document.getElementById('colorPreview');
colorInput.addEventListener('input', () => {
colorPreview.style.backgroundColor = colorInput.value;
});
// Initialize the preview with the default color
colorPreview.style.backgroundColor = colorInput.value;
</script>
</body>
</html>本题详细解读
1. HTML 结构
<div class="color-picker">: 这是颜色选择器的容器,包含颜色预览区域和颜色选择输入框。<div class="color-preview">: 用于显示当前选中的颜色。<input type="color">: 这是HTML5提供的颜色选择输入框,用户可以通过它选择颜色。
2. CSS 样式
.color-picker: 使用Flexbox布局,使颜色预览区域和输入框垂直居中排列。.color-preview: 设置了一个固定大小的预览区域,并添加了边框以便于区分。
3. JavaScript 逻辑
colorInput.addEventListener('input', ...): 监听颜色选择输入框的input事件,当用户选择颜色时,更新颜色预览区域的背景颜色。colorPreview.style.backgroundColor = colorInput.value;: 将颜色预览区域的背景颜色设置为用户选择的颜色。
4. 初始化
- 在页面加载时,颜色预览区域的背景颜色会被初始化为颜色选择输入框的默认值(
#ff0000)。
这个简单的颜色选择器利用了HTML5的原生颜色选择输入框,结合JavaScript动态更新预览区域的颜色,实现了一个基本的颜色选择功能。