原生js实现九宫格抽奖动画
样式及代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<style>
.wrap {
display: flex;
flex-wrap: wrap;
}
.wrap li {
width: 33.33%;
height: 100px;
background: pink;
list-style: none;
display: flex;
justify-content: center;
align-items: center;
border: 3px solid white;
box-sizing: border-box;
}
.ck {
width: 33.33%;
height: 100px;
background: pink;
list-style: none;
display: flex;
justify-content: center;
align-items: center;
border: 3px solid red !important;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="wrap">
<li class="item">1</li>
<li class="item">2</li>
<li class="item">3</li>
<li class="item">4</li>
<li class="item-5">抽奖</li>
<li class="item">6</li>
<li class="item">7</li>
<li class="item">8</li>
<li class="item">9</li>
</div>
<script>
$(function () {
var item = document.querySelectorAll(".item");
var isStart = true;
var time = null;
var speed = 100;
var index = 0;
var save = null;
var count = 0;
var num = 0;
var arr = item.length;
$('.item-5').on('click', function () {
if (isStart) {
isStart = false;
index = Math.floor(Math.random() * arr);
console.log('index: ', index);
Rotate();
}
})
function Rotate() {
if (num >= item.length) {
num = 0;
count++;
}
if (save) {
save.classList.remove("ck");
}
item[num].classList.add("ck");
save = item[num];
if (count < 6) {
speed -= 2;
} else {
speed += 30;
}
if (speed <= 10) {
speed = 10;
}
if (count >= 8 && num == index) {
clearTimeout(time);
return;
}
num++;
time = setTimeout(Rotate, speed);
}
})
</script>
</body>
</html>