知識點
- jQuery方法的連用
代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.box {
width: 300px;
height: 300px;
border: 1px solid orange;
margin: 100px auto;
}
.goods li {
width: 100px;
height: 100px;
/*background-color: red;*/
float: left;
box-sizing: border-box;
}
.goods li img {
width: 100px;
height: 100px;
}
.current {
border: 1px solid orange;
}
#begin img{
border-radius: 50%;
}
</style>
</head>
<body>
<div class="box">
<ul class="goods">
<li><img src="" alt=""></li>
<li class="current"><img src="" alt=""></li>
<li><img src="" alt=""></li>
<li><img src="" alt=""></li>
<li id="begin"><img src="" alt=""></li>
<li><img src="" alt=""></li>
<li><img src="" alt=""></li>
<li><img src="" alt=""></li>
<li><img src="" alt=""></li>
</ul>
</div>
<script type="text/javascript" src="lib/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function () {
// 0. 數據源
var goodsNames = ['耳機', '平板電腦', '感謝參與', '平板鞋', 'begin', '特步', '玩偶', 'ipone手機', '安卓手機'];
var goodsImgs = [];
for (var i = 1; i < 10; i++) {
goodsImgs.push('images/' + i + '.png');
}
// 1. 展示數據源
$('.goods>li>img').each(function (index, value) {
$(this).attr('src', goodsImgs[index]);
});
// 2. 監聽按鈕的點擊
var currentGunIndex = 0;
var showIndex = 0;
$('#begin').click(function () {
// 2.0 清除定時器
clearInterval(timer);
// 2.1 控制滾動的次數 1 <= x <= 2
var count = Math.floor(Math.random() * 8) + 8;
console.log(count);
// 滾動
// 2.2 制定滾動的路徑
var showIndexs = [0, 1, 2, 5, 8, 7, 6, 3];
// 2.3 根據路徑往回滾
var timer = setInterval(function () {
// 2.4 判斷
if(count <= 0){
if(showIndex === 2){ // 沒有中獎
alert('運氣不好哦~');
}else {
alert('恭喜中獎, 獎品是:' + goodsNames[showIndex]);
}
// 2.5 清除定時器
clearInterval(timer);
return;
}
// 2.5 條件
count --;
// 滾動的循環 1,2,3,4,5,6,7,0,1,2,3....
currentGunIndex = (currentGunIndex + 1) % showIndexs.length;
console.log(currentGunIndex);
// 從滾動路徑中找到當前盒子的下標
showIndex = showIndexs[currentGunIndex];
// console.log(showIndex);
// 2.6 讓當前的盒子被選中
$('.goods>li').eq(showIndex).addClass('current').siblings().removeClass('current');
// 2.7 控制啓動按鈕的旋轉
$('#begin').css({
'transform': 'rotate(' + (currentGunIndex - 1) * 45 +'deg)'
});
}, 200);
});
});
</script>
</body>
</html>
運行效果