頁面載入後,背景顏色在綠色系(#00ff00 到 #000000)之間持續循環漸變,形成呼吸燈般的視覺效果。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>JavaScript 漸隱漸顯背景顏色</title>
<style> A:hover { color: #00FFFF } </style>
</head>
<body onLoad="fadeIn(15)">
<script language="JavaScript">
var Color = ["ff","ee","dd","cc","bb","aa","99","88","77","66","55","44","33","22","11","00"];
function fadeIn(n) {
if (n >= 1) {
document.bgColor = "#00" + Color[n] + "00";
n -= 1;
setTimeout("fadeIn(" + n + ")", 100);
} else {
setTimeout('fadeOut(1)', 100);
}
}
function fadeOut(n) {
if (n <= (Color.length - 1)) {
document.bgColor = "#00" + Color[n] + "00";
n += 1;
setTimeout("fadeOut(" + n + ")", 100);
} else {
setTimeout("fadeIn(" + (Color.length - 1) + ")", 100);
}
}
</script>
<div>https://www.jb51.net/</div>
</body>
</html>
Color 陣列儲存十六進位綠色分量(00 到 ff),紅藍固定為 00。#000000)啟動 fadeOut。fadeIn 形成無限循環。<body onLoad="fadeIn(15)"> 從陣列索引 15(最亮)開始。現代開發建議改用 requestAnimationFrame 或 CSS @keyframes 動畫,效能更好且不阻塞主執行緒:
/* CSS 版本(推薦) */
@keyframes bgPulse {
0% { background-color: #00ff00; }
50% { background-color: #000000; }
100% { background-color: #00ff00; }
}
body { animation: bgPulse 3.2s infinite; }
但原始 JS 版本對理解定時器遞迴邏輯、十六進位顏色操作仍有教學價值。