頁面固定位置顯示輸入框,使用者輸入顏色值(如 #ff0000、red、rgb(255,0,0)),背景即時變色。
<SCRIPT LANGUAGE="JavaScript">
document.writeln('<div id="bgcolortestdiv" style="BACKGROUND-COLOR: gray; POSITION: absolute; width:200; height:70; top:100; Z-INDEX: 100" align="center">');
document.writeln('<p><b><font size=2>輸入顏色代碼<br>可以即時改變背景色</font></b></p>');
document.writeln('<p><input type="text" name="text" onkeyup="cbgcolor(this.value)"></p>');
document.writeln('</div>');
function cbgcolor(color) {
if (color) document.bgColor = color;
}
function keepdivpos() {
document.all.bgcolortestdiv.style.pixelTop = document.body.scrollTop + 100;
}
setInterval('keepdivpos()', 100); // 固定定位跟隨捲動
</SCRIPT>
<div id="color-picker" class="color-picker">
<label>背景色:<input type="text" id="color-input" placeholder="#ff0000 或 red"></label>
<input type="color" id="color-picker-native"> <!-- 原生色彩選擇器 -->
</div>
.color-picker {
position: fixed; top: 20px; right: 20px; z-index: 9999;
background: rgba(0,0,0,0.7); color: white; padding: 10px; border-radius: 4px;
font-family: sans-serif; font-size: 14px;
}
.color-picker input { margin-left: 8px; padding: 4px 8px; }
const colorInput = document.getElementById('color-input');
const colorPicker = document.getElementById('color-picker-native');
// 同步兩個輸入框
colorInput.addEventListener('input', () => {
document.body.style.backgroundColor = colorInput.value;
// 同步原生 color picker(需合法 hex 格式)
if (/^#[0-9a-fA-F]{6}$/.test(colorInput.value)) {
colorPicker.value = colorInput.value;
}
});
colorPicker.addEventListener('input', () => {
colorInput.value = colorPicker.value;
document.body.style.backgroundColor = colorPicker.value;
});
| 格式 | 範例 | 備註 |
|---|---|---|
| Hex | #ff0000, #f00 | 最常用 |
| RGB | rgb(255,0,0) | 標準函數記法 |
| RGBA | rgba(255,0,0,0.5) | 含透明度 |
| HSL | hsl(0,100%,50%) | 色相飽和度亮度 |
| 關鍵字 | red, tomato | CSS 命名顏色(140+) |
| 透明 | transparent | 全透明 |
const history = [];
colorInput.addEventListener('change', () => { // change: 失焦或 Enter 確認
const val = colorInput.value;
if (val && !history.includes(val)) {
history.unshift(val);
if (history.length > 10) history.pop();
renderHistory();
}
});
function renderHistory() {
// 渲染歷史色塊供快速點選
}
即時背景色預覽是表單驗證、主題定制、設計工具的常見需求。現代方案:<input type="color"> 原生選擇器 + 文字輸入同步,零依賴、無障礙、跨瀏覽器完美支援。舊代碼 document.write、document.bgColor、setInterval 定位已屬反模式,請勿在新專案使用。