最简单的方法是使用HTML5的<input type="color">
元素:
<input type="color" id="colorPicker" value="#ff0000">
优点: - 原生支持,无需额外库 - 浏览器提供标准UI - 移动设备友好
缺点: - UI在不同浏览器中差异较大 - 自定义选项有限
对于更高级的需求,可以使用专门的库:
<input type="text" id="customColorPicker">
<script>
$("#customColorPicker").spectrum({
color: "#f00",
preferredFormat: "hex",
showInput: true,
allowEmpty: true
});
</script>
<div id="pickr"></div>
<script>
const pickr = Pickr.create({
el: '#pickr',
theme: 'classic',
default: '#ff0000',
components: {
preview: true,
opacity: true,
hue: true,
interaction: {
input: true,
save: true
}
}
});
</script>
如果需要完全控制UI,可以创建自定义组件:
<div class="color-picker">
<input type="text" class="color-input" placeholder="#RRGGBB">
<div class="color-preview"></div>
<div class="color-palette">
<!-- 预定义颜色块 -->
</div>
</div>
输入框设计:
用户体验优化:
响应式设计:
无障碍访问:
<div class="custom-color-picker">
<input type="text" id="colorInput" placeholder="#RRGGBB"
pattern="^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$">
<div class="color-preview" id="colorPreview"></div>
<div class="color-palette">
<div class="color-swatch" style="background-color: #ff0000" data-color="#ff0000"></div>
<div class="color-swatch" style="background-color: #00ff00" data-color="#00ff00"></div>
<!-- 更多颜色块 -->
</div>
</div>
<script>
const colorInput = document.getElementById('colorInput');
const colorPreview = document.getElementById('colorPreview');
colorInput.addEventListener('input', function() {
if(this.checkValidity()) {
colorPreview.style.backgroundColor = this.value;
}
});
document.querySelectorAll('.color-swatch').forEach(swatch => {
swatch.addEventListener('click', function() {
const color = this.getAttribute('data-color');
colorInput.value = color;
colorPreview.style.backgroundColor = color;
});
});
</script>
<style>
.custom-color-picker {
display: flex;
align-items: center;
gap: 10px;
}
.color-preview {
width: 30px;
height: 30px;
border: 1px solid #ccc;
border-radius: 4px;
}
.color-palette {
display: flex;
gap: 5px;
}
.color-swatch {
width: 20px;
height: 20px;
cursor: pointer;
border-radius: 3px;
}
</style>
选择哪种方案取决于您的具体需求、项目复杂度和目标用户群体。对于大多数现代Web应用,使用现有的库如Pickr或Spectrum通常能提供最佳平衡。