擲骰子動畫是展示 jQuery animate() 鏈式呼叫、CSS Sprite 幀切換、隨機數生成與防重複點擊的經典案例。本文完整拆解實現原理、素材準備、CSS 定位、動畫時序控制與遮罩防抖邏輯。
dice.pngbackground-position 切換顯示不同幀將以下幀垂直排列於 dice.png:
.wrap { width: 90px; height: 90px; margin: 120px auto 30px; position: relative; }
.dice { width: 90px; height: 90px; background: url(dice.png) no-repeat; }
.dice_1 { background-position: -5px -4px; }
.dice_2 { background-position: -5px -107px; }
.dice_3 { background-position: -5px -212px; }
.dice_4 { background-position: -5px -317px; }
.dice_5 { background-position: -5px -427px; }
.dice_6 { background-position: -5px -535px; }
.dice_t { background-position: -5px -651px; } /* 過渡幀1 */
.dice_s { background-position: -5px -763px; } /* 過渡幀2 */
.dice_e { background-position: -5px -876px; } /* 過渡幀3 */
#dice_mask {
width: 90px; height: 90px; background: #fff; opacity: 0;
position: absolute; top: 0; left: 0; z-index: 999;
}
$(function() {
var $dice = $("#dice");
$dice.click(function() {
// 1. 重置狀態
$dice.attr("class", "dice").css("cursor", "default");
// 2. 加遮罩防重複點擊
$(".wrap").append("");
// 3. 產生隨機點數 1-6
var num = Math.floor(Math.random() * 6) + 1;
// 4. 動畫序列:位移 → 過渡幀 → 延遲 → 顯示結果
$dice.animate({ left: '+2px' }, 100, function() {
$dice.addClass("dice_t"); // 過渡幀1
}).delay(200).animate({ top: '-2px' }, 100, function() {
$dice.removeClass("dice_t").addClass("dice_s"); // 過渡幀2
}).delay(200).animate({ opacity: 'show' }, 600, function() {
$dice.removeClass("dice_s").addClass("dice_e"); // 過渡幀3
}).delay(100).animate({ left: '-2px', top: '2px' }, 100, function() {
// 5. 結束:顯示最終點數,移除遮罩
$dice.removeClass("dice_e").addClass("dice_" + num);
$("#result").html("您擲得點數是" + num + "");
$dice.css('cursor', 'pointer');
$("#dice_mask").remove();
});
});
});
| 技術 | 作用 | 關鍵 API |
|---|---|---|
| CSS Sprite | 減少 HTTP 請求、避免圖片閃爍 | background-position |
| animate() 鏈式 | 序列動畫,回調函數保證順序 | .animate().delay().animate() |
| 類別切換 | 切換背景定位實現幀變化 | .addClass() / .removeClass() |
| 遮罩層防抖 | 動畫期間阻擋點擊 | append/remove 透明 div |
| 隨機數 | 模擬骰子公平性 | Math.random() * 6 + 1 |
作者預告下期將結合 PHP + MySQL 實現「可控制點數概率」的抽獎遊戲,核心思路:
// 使用 CSS Animation + JS 觸發,效能更好
@keyframes diceRoll {
0% { transform: translate(0,0); }
20% { transform: translate(2px,0); background-position: ...; }
40% { transform: translate(2px,-2px); background-position: ...; }
60% { opacity: 0; background-position: ...; }
80% { transform: translate(-2px,2px); background-position: ...; }
100% { transform: translate(0,0); }
}
$dice.addClass('rolling').one('animationend', () => {
$dice.removeClass('rolling').addClass('dice_' + num);
$("#dice_mask").remove();
});
這個範例展示了 jQuery 時代「用時間軸控制幀動畫」的經典思維,也是理解現代 CSS Animation / Web Animations API 的良好切入點。