wheelSurf:輪播抽獎??
概要
一款簡單便捷用于旋轉(zhuǎn)輪播抽獎的model分享給大家蜜猾。
exampleImg
(PS:示例圖和下方代碼布局不同粉渠,各位根據(jù)自己需求進行調(diào)整)
代碼
依賴庫:jQuery
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標(biāo)題文檔</title>
<link rel="stylesheet" href="./style.css">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<div id="turntable-box">
<div class="gift gift1">1</div>
<div class="gift gift2">2</div>
<div class="gift gift3">3</div>
<div class="gift gift0">8</div>
<div>
<button style="width:100px; height:100px;">com on</button>
</div>
<div class="gift gift4">4</div>
<div class="gift gift7">7</div>
<div class="gift gift6">6</div>
<div class="gift gift5">5</div>
</div>
<script src="./main.js"></script>
</body>
</html>
style.css
#turntable-box {
width: 500px;
height: 500px;
margin: 0 auto;
background-color: #dfdfdf;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: space-between;
}
#turntable-box > div {
width: 32%;
height: 32%;
border: 1px solid #000;
background-color: #fff;
box-sizing: border-box;
display: flex;
justify-content: center;
align-items: center;
}
main.js
var stopStep = 1; //表示最終獎品位置
var runT = null; //轉(zhuǎn)動方法
var step = -1; //計算轉(zhuǎn)動的步數(shù)狼荞,控制轉(zhuǎn)速和停止
var during = 8; //轉(zhuǎn)速,起始轉(zhuǎn)速為8
var isRun = false; //是否正在運行宅粥,防止重復(fù)點擊
$("button").click(function () {
if (isRun) return;
isRun = true;
stopStep = Math.floor(Math.random() * 8 + 1);
console.log('最后停止獎品位置', stopStep);
runT = setTimeout(runF, 100);
});
function runF() {
if (step >= (32 + stopStep)) { //設(shè)置轉(zhuǎn)動多少圈(獎品的倍數(shù)),當(dāng)進行步數(shù)step>=(最大步數(shù)+獎品位置步數(shù))啊楚,停止動畫吠冤,用戶獲得獎品
$(".gift" + (step % 8)).css("background-color", "#F00");
step = stopStep; //當(dāng)前獎品停止位置賦值給step,用于下次開始抽獎起始使用
isRun = false;
clearTimeout(runT); //停止轉(zhuǎn)動
alert("you get" + step);
return;
}
if (step >= (24 + stopStep)) { //在即將結(jié)束轉(zhuǎn)動前減速
during += 1;
} else { //控制中間轉(zhuǎn)速
if (during <= 2) { //保證最低轉(zhuǎn)速
during = 2;
}
during--;
}
step++;
$(".gift").each(function () {
$(this).css("background-color", "#FFF");
});
$(".gift" + (step % 8)).css("background-color", "#F00");
runT = setTimeout(runF, during * 50);
}