下拉選單選項顏色與頁面背景色同步隨機變化,選擇選項可跳轉連結。展示動態生成樣式、隨機顏色陣列、select 事件處理。
var colors = [
'#FFFFFF','#FFCCFF','#FF99FF', ... , '#000000'
]; // 共 216 個
var color1 = colors[Math.round(Math.random() * (colors.length-1))]; // select 文字色
var color2 = colors[Math.round(Math.random() * (colors.length-1))]; // select 背景色
var color3 = colors[Math.round(Math.random() * (colors.length-1))]; // body 背景色
var css = '<style type="text/css">'
+ 'select{width:300px;height:118px;overflow:hidden;font-family:times new roman;font-size:14px;color:' + color1 + ';background:' + color2 + ';}'
+ 'body{background:' + color3 + ';}'
+ 'td{font-family:times new roman;font-size:14px;color:#000000;}'
+ '</style>';
document.writeln(css);
function show(file) {
var url = file.options[file.selectedIndex].value;
if (document.all || document.layers) location.href = url;
else if (document.getElementById && url != undefined) location.href = url;
}
<select name="showoff" id="showoff" size="3" onChange="show(document.form.showoff)">
<option value="https://www.163.com">163網易</option>
<option value="https://www.baidu.com">百度搜索</option>
</select>
document.writeln 阻塞渲染、破壞 DOM 結構、難以維護。onChange、瀏覽器嗅探 document.all 過時。<style>
:root { --select-text: #333; --select-bg: #fff; --body-bg: #fafafa; }
select { color: var(--select-text); background: var(--select-bg); width: 300px; height: 118px; }
body { background: var(--body-bg); transition: background 0.3s; }
</style>
<select id="site-select">
<option value="https://www.163.com">163網易</option>
<option value="https://www.baidu.com">百度搜索</option>
</select>
<script>
const colors = ['#333','#666','#999','#ccc','#fff','#f00','#0f0','#00f','#ff0','#f0f','#0ff']; // 示例
const pick = () => colors[Math.floor(Math.random()*colors.length)];
function applyRandomColors() {
document.documentElement.style.setProperty('--select-text', pick());
document.documentElement.style.setProperty('--select-bg', pick());
document.documentElement.style.setProperty('--body-bg', pick());
}
// 頁面載入即隨機
applyRandomColors();
// 可選:按鈕手動換色
document.getElementById('change-btn')?.addEventListener('click', applyRandomColors);
// Select 跳轉 (現代寫法)
document.getElementById('site-select').addEventListener('change', function() {
if (this.value) window.open(this.value, '_blank');
});
</script>
| 技術點 | 原始寫法 | 現代重構 |
|---|---|---|
| 樣式注入 | document.writeln(<style>...) | CSS 變數 + style.setProperty |
| 隨機色 | Math.round(Math.random()*(len-1)) | Math.floor(Math.random()*len) (標準) |
| 事件綁定 | 內聯 onChange + 瀏覽器嗅探 | addEventListener('change') |
| 跳轉 | location.href | window.open(url, '_blank') (新分頁) |
此範例展示了早期「動態寫入 Style 標籤」的隨機配色技巧。現代開發應採用 CSS 變數 + 事件監聽器,分離關注點,確保可維護性與無障礙。隨機色生成需注意對比度(WCAG AA 級建議 4.5:1),可引入 chroma.js 或自行實現亮度檢查。