js 简单轮播图
<!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-sizing: border-box;
}
.carousel-box {
width: 500px;
height: 400px;
}
img {
width: 100%;
height: 285px;
}
.sub-box {
position: relative;
top: -8%;
background-color: rgba(0, 0, 0, 0);
}
ul {
margin: 0 auto;
width: 100px;
height: 10%;
display: flex;
justify-content: space-around;
}
li {
width: 10px;
height: 10px;
list-style: none;
border: 1px solid white;
border-radius: 50%;
}
.active {
background-color: white;
}
</style>
</head>
<body>
<div class="carousel-box">
<div class="img-box">
<img src="./image/1.jpg">
</div>
<div class="sub-box">
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
<script>
const imgBox = [
{ url: './image/1.jpg' },
{ url: './image/2.jpg' },
{ url: './image/3.jpg' },
{ url: './image/4.jpg' },
{ url: './image/5.jpg' },
]
const img = document.querySelector('img');
const sub = document.querySelectorAll('.sub-box li');
let n = 0;
setInterval(function () {
if (n >= imgBox.length - 1) {
n = 0;
img.src = `./image/1.jpg`;
} else {
n++;
img.src = `./image/${n + 1}.jpg`;
console.log(n);
}
document.querySelector('.active').classList.remove('active');
sub[n].classList.add('active');
}, 1000)
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/70677f63239fdf37d800dbadd47520f6.png#pic_center)