DIV CSS 佈局教程網

用 JS 讓網頁背景色與下拉選單顏色同步變化
編輯:關於JavaScript     

這個範例示範如何讓頁面背景與一個 select 下拉選單的配色同步改變。程式會從一組預先定義好的色碼陣列中隨機挑選顏色,套用到文字、背景與表單上,讓畫面每次都煥然一新。完整做法如下:

復制代碼 代碼如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JS實現網頁背景顏色與select框中的顏色同時變化</title>
</head>
<body>
<script language="javascript">
colors = new Array('#FFFFFF','#FFCCFF','#FF99FF','#FF66FF','#FF33FF','#FF00FF','#FFFFCC','#FFCCCC','#FF99CC','#FF66CC','#FF33CC','#FF00CC', /* …更多色碼… */ '#000000');
function show(file){
var url = file.options[file.selectedIndex].value;
if(document.all || document.layers)
location.href = url;
else if(document.getElementById){
if(url != undefined)
location.href = url;
}
}
var color1 = colors[Math.round(Math.random() * (colors.length-1))];
var color2 = colors[Math.round(Math.random() * (colors.length-1))];
var color3 = colors[Math.round(Math.random() * (colors.length-1))];
var streng = '<style type="text/css">select{width:300; height:118; overflow:hidden; font-family:times new roman; font-size:14px; color:';
streng += color1 + '; background:' + color2 + ';}body{background:' + color3 + ';}td{font-family:times new roman; font-size:14px; color:#000000;}</style>';
document.writeln(streng);
</script>
<table border="0" cellspacing="0" cellpadding="0" width="500">
<form name="form" target="_blank">
<tr><td>
<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>
</td></tr>
</form>
</table>
</body>
</html>

關鍵在於用 Math.random() 隨機取色,再透過 document.writeln 動態寫入一組 <style>,讓 select 與 body 共用同一批色彩。這個小技巧很適合用來為頁面增添活潑的視覺變化。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved