在线访问demo和代码在底部
代码,复制就可以跑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🐯🐯🐯</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
width: 300px;
height: 300px;
border: 1px solid grey;
}
.item {
width: 80px;
height: 80px;
position: absolute;
background-color: gainsboro;
display: flex;
justify-content: center;
align-items: center;
}
.item.active {
background-color: red;
font-weight: 600;
}
</style>
</head>
<body>
<h1 id="result">这一次结果</h1>
<div class="box" id="box"></div>
<button id="start">开始</button>
<script>
let box = document.querySelector("#box")
let start = document.querySelector("#start")
let result = document.querySelector("#result");
//奖项个数
const itemLen = 8;
let arr = [];
//开启位置
let startIndex = 0;
let timer = null;
let speed = 80;
//随机工具函数
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//基础圈数
let baseTarget = getRandomNumber(4, 6) * itemLen;
//开奖索引
let targetIndex = null;
//基础圈数+开奖索引
let totalCount = 0;
//初始化dom渲染
for (let i = 0; i < itemLen; i++) {
arr.push("奖项:" + i)
}
let domStr = document.createDocumentFragment();
const domItems = []
for (let i = 0; i < arr.length; i++) {
let dom = document.createElement("div");
dom.className = "item";
dom.innerHTML = arr[i];
switch (i) {
case 0:
dom.style.top = 0;
dom.style.left = 0;
break;
case 1:
dom.style.top = 0;
dom.style.left = "110px";
break;
case 2:
dom.style.top = 0;
dom.style.right = 0;
break;
case 3:
dom.style.top = "100px";
dom.style.right = 0;
break;
case 4:
dom.style.bottom = 0;
dom.style.right = 0;
break;
case 5:
dom.style.bottom = 0;
dom.style.right = "110px";
break;
case 6:
dom.style.bottom = 0;
dom.style.left = 0;
break;
case 6:
dom.style.bottom = "100px";
dom.style.left = 0;
break;
case 7:
dom.style.bottom = "120px";
dom.style.left = 0;
break;
}
box.appendChild(dom)
domItems.push(dom);
}
box.appendChild(domStr);
function frame() {
//清除定时器
clearTimeout(timer);
//获取递增过程的索引变量对饮奖项的索引
let currentpos = startIndex % itemLen;
//更新奖项的高亮样式
for (let i = 0; i < itemLen; i++) {
if (currentpos == i) {
domItems[i].classList.add("active");
}
else {
domItems[i].classList.remove("active");
}
}
//如果达到中奖的目标位置就停止
if (startIndex == totalCount) {
clearTimeout(timer);
return;
}
//地址的索引不断的递增
startIndex++;
//获取运行比例
let percent = Math.floor(startIndex / totalCount * 100);
//递增的索引跑了目标值的50%前都加快
if (percent <= 50) {
//需要兜底,否则会出意外
if (speed > 10) {
speed--;
}
}
else {
//后50%速度开始减速
speed += 6;
}
//这里的定时器的时间是动态的!!!!重要
timer = setTimeout(() => {
frame();
}, speed)
}
function startGame() {
//基础圈数
baseTarget = getRandomNumber(4, 6) * itemLen;
//随机目标位置
targetIndex = getRandomNumber(0, 7);
//总个数
totalCount = baseTarget + targetIndex;
result.innerHTML = "这次开奖的结果:" + arr[targetIndex];
startIndex = 0;
//初始化速度
speed = 80;
//重置完所有配置后,开始跑定时器
frame();
}
start.onclick = startGame;
</script>
</body>
</html>
在线demo
代码在这,请直接品尝JS Bin - Collaborative JavaScript Debugging