<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.wrap {
width: 480px;
height: 360px;
margin: auto;
border: 1px solid #000;
position: relative;
}
.left, .right {
width: 30px;
height: 20px;
background: rgba(29, 255, 181, 0.55);
position: absolute;
margin: auto;
top: 0;
bottom: 0;
text-align: center;
color: #061f3e;
line-height: 20px;
cursor: pointer;
}
.left:hover, .right:hover {
background: #15ffa7;
}
.left {
left: 10px;
}
.right {
right: 10px;
}
.dots {
display: flex;
width: 100px;
justify-content: space-between;
position: absolute;
margin: auto;
left: 0;
right: 0;
bottom: 10px;
}
.dots > span {
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
background: #fff;
}
.active {
background: red;
}
</style>
</head>
<body>
<div class="wrap">
<img src="" alt="">
<div class="left"><</div>
<div class="right">></div>
<div class="dots">
<span></span><span></span><span></span><span></span>
</div>
</div>
<script>
window.addEventListener("load", () => {
function $(ele) {
return document.querySelector(ele)
}
function $s(eles) {
return document.querySelectorAll(eles)
}
const imgArr = [
"http://cdn.jirengu.com/book.jirengu.com/img/1.jpg",
"http://cdn.jirengu.com/book.jirengu.com/img/2.jpg",
"http://cdn.jirengu.com/book.jirengu.com/img/3.jpg",
"http://cdn.jirengu.com/book.jirengu.com/img/4.jpg",
];
const dots = $s(".dots>span");
const [wrap, img, left, right] = [$(".wrap"), $("img"), $(".left"), $(".right")];
let timer = null;
let count = 0;
function autoLoop(num=1) {
count += num;
if (count > imgArr.length - 1) {
count = 0
}
if (count < 0) {
count = imgArr.length - 1
}
img.src = imgArr[count];
for (let i = 0; i < dots.length; i++) {
if (i === count) {
dots[i].style.backgroundColor = "red";
} else {
dots[i].style.backgroundColor = "#fff"
}
}
}
function changeDot(btn) {
for (let i = 0; i < btn.length; i++) {
btn[i].index = i;
btn[i].onclick = function () {
for (let j = 0; j < btn.length; j++) {
btn[j].style.backgroundColor = "#fff";
btn[this.index].style.backgroundColor = "red";
img.src = imgArr[this.index]
}
}
}
}
img.setAttribute("src", imgArr[count]);
timer = setInterval(autoLoop, 1000);
right.onclick = () => {
autoLoop(1)
};
left.onclick = () => {
autoLoop(-1)
};
wrap.onmouseover = () => {
clearInterval(timer)
};
wrap.onmouseleave = () => {
timer = setInterval(autoLoop, 1000)
};
changeDot(dots);
})
</script>
</body>
</html>