這個小特效適合用於活動頁或 loading 畫面:黑底上不斷冒出大小不一的星星,位置隨機,點一下它就消失。實作上它同時示範了動態建立元素、隨機數運算與事件綁定三件事。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>隨機星星特效</title>
<script type="text/javascript">
// 星星尺寸範圍
var img_width_min = 15;
var img_width_max = 80;
// 可放置的座標範圍,初始化時才計算
var x_left = 0;
var x_right = 0;
var y_top = 0;
var y_bottom = 0;
function init() {
document.body.bgColor = "#000";
// 用視窗尺寸減去最大星星寬,確保不會超出畫面
x_right = window.innerWidth - img_width_max;
y_bottom = window.innerHeight - img_width_max;
// 每秒生成一顆
setInterval("showStar()", 1000);
}
function showStar() {
// 動態建立一個 img 元素
var node_img = document.createElement("img");
// 隨機決定尺寸與位置
var width = getRandom(img_width_min, img_width_max);
var x = getRandom(x_left, x_right);
var y = getRandom(y_top, y_bottom);
node_img.setAttribute("src", "images/xingxing.gif");
// 絕對定位 + 隨機座標與寬度
var style = "position:absolute;left:" + x + "px;top:" + y + "px;";
style += "width:" + width + "px;";
node_img.setAttribute("style", style);
// 綁定點擊移除
node_img.setAttribute("onclick", "removeImg(this)");
// 掛到 body 底下
document.body.appendChild(node_img);
}
function removeImg(obj) {
document.body.removeChild(obj);
}
// 回傳 [min, max) 區間內的整數
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
</script>
</head>
<body onload="init()">
</body>
</html>
隨機公式怎麼來。Math.random() 回傳 0(含)到 1(不含)之間的小數。乘上 max - min 得到區間寬度,加上 min 平移到目標區間,最後用 Math.floor 取整數。這個公式值得背下來,之後做雨滴、雪花、粒子效果都會用到。
座標上限要扣掉元素尺寸。如果 y 直接取到 window.innerHeight,星星會有一半跑出畫面外。範例用視窗尺寸減去星星的最大寬度,就是為了避免這種情況。更精確的做法是先知道這顆星星的實際尺寸,再逐一計算它的可用範圍。
事件用 this 傳參。用 setAttribute("onclick", "removeImg(this)") 時,this 會在被點擊時指向該 img 元素,函式就能直接把它從 DOM 上摘掉。若改用 addEventListener,則可以直接寫成 node_img.addEventListener('click', function(){...}),不必拼字串。
元素會無限累積。這個版本只負責新增與點擊移除,如果使用者不點,星星就會一直堆在頁面上,最終拖慢效能。實務上有三種處理:為星星加上淡出後自動移除的計時器、限制同屏最大數量、或定期清空舊元素。這也是所有「持續生成節點」的特效都必須回答的問題。
window.innerWidth 的相容性。舊版 IE 使用 document.documentElement.clientWidth,實作時通常會寫成 window.innerWidth || document.documentElement.clientWidth 以兼顧兩邊。
把隨機公式、座標約束與生命週期管理這三件事掌握好,這套骨架稍換素材就能改造成下雪、煙火或鍵盤敲擊特效。