使用原生 HTML、CSS 與 JavaScript 實作一個輕量級顏色選擇器,支援 4096 種顏色(16×16×16 簡易色盤),提供滑鼠懸停預覽與點擊確認功能,無需外部庫。
<input id="txtColor" type="text" placeholder="點選顏色" />
<div class="divColor" id="colorPanel"></div>
.divColor div { float:left; width:10px; height:10px; cursor:pointer; }
.divColor span { display:block; float:left; width:30px; height:20px; cursor:pointer; }
.clear { clear:both; font-size:0; line-height:0; }
#000 到 #FFF 的灰階色塊(span)。onclick="setColor(...)" 與 onmouseover="showColor(...)"。selectColor(input):輸入框聚焦時重設背景與邊框。showColor(hex):滑鼠懸停即時更新輸入框邊框顏色。setColor(hex):點擊寫入輸入框值、背景色,並自動選取文字方便複製。將以下代碼存為 color-picker.html 直接在瀏覽器開啟即可使用:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>JS 顏色選擇器</title>
<style>
.divColor div{float:left;width:10px;height:10px;cursor:pointer}
.divColor span{display:block;float:left;width:30px;height:20px;cursor:pointer}
.clear{clear:both;font-size:0;line-height:0}
#txtColor{border:4px solid #333;padding:4px;width:120px;font-family:monospace}
</style></head><body>
<input id="txtColor" type="text" placeholder="點選下方色塊" />
<div class="divColor" id="panel"></div>
<script>
const panel=document.getElementById('panel'), input=document.getElementById('txtColor');
const hex='0123456789ABCDEF';
// 灰階列
for(let r=0;r<16;r++){
const c='#'+hex[r].repeat(3);
panel.innerHTML+=`<span onclick="set('${c}')" onmouseover="show('${c}')" style="background:${c}"></span>`;
}
panel.innerHTML+=`<div class="clear"></div>`;
// 色盤
for(let block=0;block<2;block++){
const base=block*8;
for(let r=0;r<16;r++){
panel.innerHTML+=`<div class="clear">`;
for(let g=base;g
<input type="color"> 原生選色器作為備援。localStorage。.clear 清除浮動。