九宫格抽奖
最近在玩一款西游除魔的小程序游戏,遇到一个九宫格抽奖的活动,然后就想模拟一个九宫格抽奖的程序。
问题
随机数
每次点击产生一个随机数,来确认旋转的位置
let times = parseInt(Math.random() * 10 + 10);
如何顺时针旋转
首先使用数组列出旋转的顺序,然后使用下标来保证能顺时针完成
//保证顺时针旋转
const arr = [0, 1, 2, 4, 7, 6, 5, 3];
// 清除所有active类
document.querySelectorAll(".grid-item").forEach((item) => {
item.classList.remove("active");
});
// 指定位置添加背景
commonList[arr[i]].classList.add("active");
具体代码
let clickItem = document.querySelector(".click");
let commonList = document.querySelectorAll(".common");
//顺时针旋转
const arr = [0, 1, 2, 4, 7, 6, 5, 3];
clickItem.addEventListener("click", () => {
let times = parseInt(Math.random() * 10 + 10);
let i = 0;
let index = 0;
let timer = setInterval(() => {
if (index === times) {
clearInterval(timer);
}
if (i > 7) {
i = 0;
}
// 清除所有active类
document.querySelectorAll(".grid-item").forEach((item) => {
item.classList.remove("active");
});
commonList[arr[i]].classList.add("active");
i++;
index++;
}, 100);