<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图</title>
<link rel="stylesheet" href="./css/07.css">
</head>
<body>
<div class="round">
<!-- 图片 -->
<ul class="img">
<li><img src="./img/23d7dbb1b96a146a.jpg.webp"></li>
<li><img src="./img/4fe0dcb5ab6dc357.jpg.webp"></li>
<li><img src="./img/590x470.jpg"></li>
<li><img src="./img/bb571108797afb8c.jpg.webp"></li>
<li><img src="./img/fe799a940b971ec9.jpg.webp"></li>
</ul>
<!-- 圆点 -->
<ul class="point">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script src="./js/07.js"></script>
<script>
new Round('.round').autoplay(3000);
</script>
</body>
</html>
js编写
class Round{
constructor(selector){
// 事件源
this.points = document.querySelectorAll(`${selector}>.point>li`);
// 拿到所有图片
this.imgs = document.querySelectorAll(`${selector}>.img>li`);
// 定时器id
this.sid = 0;
// 当前显示的图片的id
this.showid = 0;
this.init();
// 当鼠标移入当前区域,自动轮播暂停
let _this = this;
document.querySelector(selector).onmouseover = function(){
clearInterval(_this.sid);
}
document.querySelector(selector).onmouseout = function(){
console.log(_this.sid);
// 是否开启了自动轮播
if(_this.sid){
_this.autoplay();
}
}
}
init(){
// 循环的方式给每个事件源绑定事件
let _this = this;
for (let i = 0; i < this.points.length; i++) {
this.points[i].onclick = function(){
console.log(i);
// 隐藏所有的图片,并把对应的图片显示出来
// Cannot read property 'length' of undefined
for (let j = 0; j < _this.imgs.length; j++) {
_this.imgs[j].style.display = 'none';
}
// 需要记录当前现实的图片的id
_this.showid = i;
_this.imgs[i].style.display = 'block';
}
}
}
autoplay(step = 1000){
let _this = this;
let n = _this.showid;
this.sid = setInterval(function(){
_this.points[++n % _this.points.length].click();
}, step);
}
}
css编写
*{
margin: 0;
padding: 0;
}
li{
list-style: none;
}
.round{
width: 590px;
height: 470px;
background-color: #f02;
margin: 50px auto;
font-size: 0;
/* 超出部分隐藏 */
overflow: hidden;
/* 子绝父相 */
position: relative;
}
.round li{
display: inline-block;
}
.point{
display: flex;
justify-content: center;
position: absolute;
bottom: 10px;
width: 100%;
left: 0;
}
.point>li{
width: 10px;
height: 10px;
background-color: #cfcccc;
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
margin-left: 5px;
cursor: pointer;
}