紅金配色的大轉盤,是年節活動、會員回饋與門市慶祝時最常見的互動橋段。這個範例以一張轉盤底圖搭配 CSS 定位排版,再借助 jQuery 旋轉外掛驅動指針:每按一次就先多轉幾圈,最後精準停在事先計算好的角度上,並彈出對應的獎項訊息。
線上體驗:https:///keleyi/phtml/jqtexiao/33.htm
抽獎區其實只有三個關鍵角色:轉盤容器 .rotary、指針 #rotaryArrow,以及負責顯示結果的浮層 #result。右側的中獎名單只是視覺陪襯,用一組 li 條列即可,號碼刻意遮成 1569****851 這種形式,兼顧畫面與隱私。
<div class="rotary">
<div class="rotaryArrow" id="rotaryArrow"></div>
<div class="list">
<h3>中獎名單</h3>
<ul><li>1569****851</li><!-- 其餘名單省略 --></ul>
</div>
<div class="result" id="result">
<p id="resultTxt"></p>
<a href="javascript:" id="resultBtn" title="關閉">關閉</a>
</div>
</div>
核心概念是「先抽獎,再算角度」。點擊時從獎項陣列中隨機取一個索引,用 switch 對應到該扇區的角度,再把角度加上 1440 度(也就是整整四圈),讓動畫看起來有足夠的力道與期待感。
$(function(){
var $rotaryArrow = $('#rotaryArrow'),
$result = $('#result'),
$resultTxt = $('#resultTxt');
$rotaryArrow.click(function(){
var data = [0,1,2,3,4,5,6,7];
data = data[Math.floor(Math.random() * data.length)];
switch(data){
case 1: rotateFunc(1, 87, '恭喜您獲得了 <em>1</em> 元代金券'); break;
case 2: rotateFunc(2, 43, '恭喜您獲得了 <em>5</em> 元代金券'); break;
case 3: rotateFunc(3, 134, '恭喜您獲得了 <em>10</em> 元代金券'); break;
case 4: rotateFunc(4, 177, '很遺憾,這次未抽中獎,繼續加油吧'); break;
case 5: rotateFunc(5, 223, '恭喜您獲得了 <em>20</em> 元代金券'); break;
case 6: rotateFunc(6, 268, '恭喜您獲得了 <em>50</em> 元代金券'); break;
case 7: rotateFunc(7, 316, '恭喜您獲得了 <em>30</em> 元代金券'); break;
default:rotateFunc(0, 0, '很遺憾,這次未抽中獎,繼續加油吧');
}
});
var rotateFunc = function(awards, angle, text){
$rotaryArrow.stopRotate();
$rotaryArrow.rotate({
angle: 0,
duration: 5000,
animateTo: angle + 1440,
callback: function(){
$resultTxt.html(text);
$result.show();
}
});
};
$('#resultBtn').click(function(){ $result.hide(); });
});
rotate 疊加。jquery.rotate.min.js 兩個腳本,樣式則集中在 style.css。本範例僅供學習交流使用,請勿用於商業用途。