<link rel="stylesheet" href="./通用样式.css">
<style>
.contain {
width: 1200px;
height: 800px;
margin: 50px auto;
}
li,
.box {
border: 1px solid green;
width: 150px;
height: 150px;
background-color: skyblue;
text-align: center;
line-height: 150px;
font-weight: bold;
margin-left: 5px;
}
button {
width: 50px;
height: 50px;
cursor: pointer;
}
.active {
background-color: #cccccc;
}
</style>
</head>
<body>
<div class="contain">
<ul class="flex">
<li class="active" roll='1'>600元优惠卷</li>
<li roll='2'>800元优惠卷</li>
<li roll='0'>900元优惠卷</li>
</ul>
<ul class="flex">
<li roll='3'>600元优惠卷</li>
<div class="flex j-s-a box a-i-c" roll='8'>
<button class="start">开始</button>
<button class="stop">停止</button>
</div>
<li roll='4'>900元优惠卷</li>
</ul>
<ul class="flex">
<li roll='5'>600元优惠卷</li>
<li roll='6'>800元优惠卷</li>
<li roll='2'>900元优惠卷</li>
</ul>
</div>
<script>
//获取按钮
let start = document.querySelector('.start')
let stop = document.querySelector('.stop')
let list = document.querySelectorAll('ul>li')
let index = 0
//定义一个变量接收定时器
let timer = null
start.onclick = function () {
//在每次开始时清除定时器,避免定时器的多开
clearInterval(timer)
timer = setInterval(() => {
for (let i = 0; i < list.length; i++) {
//把所有li标签里的元素的背景颜色换成skyblue
list[i].style.backgroundColor = 'skyblue'
}
for (let j = 0; j < list.length; j++) {
//利用getAttribute获取上方的roll的字符串在利用number转化为数字
//因为按钮里面的元素getAttribute的值为8 8除以8余数为0,
// 所有第一个元素背景颜色加上grey,随后直接跳出循环
if (Number(list[j].getAttribute('roll')) == index % 8) {
list[j].style.backgroundColor = 'grey'
break;
}
}
//每次给初始的index的值加1
index++
}, 60);
}
stop.onclick = function () {
//当鼠标点击停止时,直接清除定时器,从而达到停止
clearInterval(timer)
}
</script>
</body>