舉例如下
function run() {
var c = randomColor();
document.bgColor = c;
}
function randomColor() {
var c1 = (Math.random() * 1000) % 256;
var c2 = (Math.random() * 1000) % 256;
var c3 = (Math.random() * 1000) % 256;
c1 = hex(Math.floor(c1));
c2 = hex(Math.floor(c2));
c3 = hex(Math.floor(c3));
return "#" + c1 + c2 + c3;
}
function hex(n) {
var result = "";
var temp, count;
while (n > 16) {
count = 1;
while (n > exp(16, count)) {
count += 1;
}
count -= 1;
temp = n / exp(16, count);
temp = Math.floor(temp);
result += hexLetter(temp);
n -= exp(16, count) * temp;
}
if (n == 16) {
result += "1";
n -= 16;
}
result += hexLetter(n);
return result;
}
function hexLetter(n) {
if (n >= 16 || n < 0) {
return "";
}
else {
switch (n) {
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
default:
return "" + n;
}
}
}
function exp(x, y) {
var result = 1;
while (y > 0) {
result *= x;
y -= 1;
}
return result;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:document005.js
功能:示範 JavaScript 程式
作者:張凱慶
時間:西元 2011 年 8 月 */此例是藉由 randomColor() 函數 (function) 產生隨機的顏色,然後在 run() 中
document.bgColor = c;
將顏色指派給 document.bgColor ,文件背景顏色就會變換成所產生的隨機顏色。
我們以下面的 HTML 文件載入
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM DEMO</title>
<script src="document005.js" type="text/javascript"></script>
</head>
<body>
<input type="button" value="RUN" onclick="run();">
</body>
</html>
<!-- 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:document005.html
功能:示範 JavaScript 程式
作者:張凱慶
時間:西元 2011 年 8 月 -->瀏覽器 (broswer) 開啟,按下 RUN 就會改變背景顏色

| 中英文術語對照 | |
|---|---|
| 函數 | function |
| 瀏覽器 | broswer |
您可以繼續參考
基本概念
文件物件 document
- 屬性
- document.activeElement
- document.alinkColor
- document.anchors
- document.bgColor
- document.cookie
- document.documentElement
- document.documentURI
- document.forms
- document.images
- document.inputEncoding
- document.lastModified
- document.lastStyleSheetSet
- document.linkColor
- document.links
- document.location
- document.plugins
- document.preferredStyleSheetSet
- document.readyState
- document.referrer
- document.selectedStyleSheetSet
- document.styleSheets
- document.styleSheetSets
- document.title
- document.URL
- document.vlinkColor
- 方法
- document.close()
- document.createAttribute(name_str)
- document.createElement(element_str)
- document.createTextNode(text_str)
- document.enableStyleSheetsForSet(ss_str)
- document.getElementById(id_str)
- document.getElementsByClassName(cn_str)
- document.getElementsByName(n_str)
- document.getElementsByTagName(tn_str)
- document.hasFocus()
- document.open()
- document.write(str)
- document.writeln(str)
相關目錄
HTML DOM 快速導覽
JavaScript 教材
首頁
參考資料
https://developer.mozilla.org/en/DOM/document.bgColor
http://msdn.microsoft.com/en-us/library/ms533506(VS.85).aspx
沒有留言:
張貼留言