點擊「拆紅包」按鈕,紅包抖動一會兒後顯示結果。可以自訂獎品清單,每次拆開隨機抽出一項,且支援重複抽獎。
線上體驗:https://hovertree.com/texiao/js/37/
掃描下方 QR Code 也可直接體驗:

效果預覽:

完整程式碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title>搖紅包</title>
<link rel="stylesheet" href="https://hovertree.com/texiao/js/37/css/csshake.min.css">
<link rel="stylesheet" href="https://hovertree.com/texiao/js/37/css/style.css">
<script src="https://hovertree.com/texiao/js/37/js/zepto.min.js"></script>
<script src="https://hovertree.com/texiao/js/37/js/red.js"></script>
</head>
<body>
<!-- 紅包 -->
<div class="red">
<span style="background-image: url(https://hovertree.com/texiao/js/37/img/red-w.png);"></span>
<button class="redbutton" type="button" id="hovertreeOpen">拆紅包</button>
<div class="red-jg">
<h1 id="hwqKey">何問起</h1>
<h5 id="hwqValue">我喜歡你!</h5>
</div>
</div>
<!-- End 紅包 -->
<!-- 再抽一次 -->
<div class="t-btn">
<button id="hewenqiAgain">再抽一次</button>
</div>
<div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';">
<p>來源:<a href="https://hovertree.com/" target="_blank">何問起</a></p>
</div>
<script>
function hoverTreeRandom(n) {
return Math.floor(Math.random() * n + 1);
}
var hovertreePrize = new Array();
hovertreePrize[0] = { "key": "恭喜您:", "value": "獲得 88 元代金券!" };
hovertreePrize[1] = { "key": "恭喜您:", "value": "獲得蘋果八袋!" };
hovertreePrize[2] = { "key": "祝願您:", "value": "新年快樂,大吉大利!" };
hovertreePrize[3] = { "key": "祝願您:", "value": "笑口常開,天天開心!" };
hovertreePrize[4] = { "key": "祝願您:", "value": "事業順利,財源滾滾!" };
var h_index = 0;
document.getElementById("hovertreeOpen").addEventListener("click", function () {
h_index = hoverTreeRandom(hovertreePrize.length) - 1;
document.getElementById("hwqKey").innerText = hovertreePrize[h_index].key;
document.getElementById("hwqValue").innerText = hovertreePrize[h_index].value;
});
document.getElementById("hewenqiAgain").addEventListener("click", function () {
location = "https://hovertree.com/texiao/js/37/";
});
</script>
</body>
</html>
原始碼下載:https://hovertree.com/h/bjag/1hiwd73v.htm
另一個紅包特效:https://hovertree.com/h/bjaf/mcpnogp6.htm
幾點值得改進的地方
抽獎邏輯本身用了 hoverTreeRandom,它回傳 1 到 n 的整數,因此取索引時要減 1。這個寫法沒錯,但更常見的形式是 Math.floor(Math.random() * arr.length),直接得到 0 到 n−1,不必再補償。
「再抽一次」目前是用 location 重新載入整個頁面,動畫才會重播。這在靜態展示上夠用,但正式環境下重新載入有明顯延遲,更好的做法是把抖動動畫的 class 移除後用 void offsetWidth 觸發重排再加上去,就能原地重播,不必刷新。
最後也是最重要的:如果這是真的抽獎活動,絕對不能只靠前端決定結果。所有抽獎邏輯都寫在瀏覽器裡,使用者開一下開發者工具就能看到完整獎項清單,甚至直接改 h_index 拿到想要的結果。正式活動必須把抽獎請求送到後端,由伺服器決定並記錄結果,前端只負責呈現動畫。同時後端也要做次數限制與去重,否則同一個人可以刷出大量中獎紀錄。