<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
#outer {
width: 690px;
height: 300px;
margin: 100px auto;
background-color: greenyellow;
padding: 10px 0;
position: relative;
overflow: hidden;
}
ul#imgList {
list-style: none;
/* width: 2800px; */
/* display: flex; */
position: absolute;
}
ul#imgList li {
float: left;
margin: 0 10px;
}
#navDiv {
display: flex;
justify-content: center;
align-items: center;
list-style: none;
align-items: flex-end;
height: 290px;
}
#navDiv a {
margin: 0 10px;
width: 10px;
height: 10px;
display: block;
background-color: red;
opacity: 0.5;
}
#navDiv a:hover {
background-color: #000;
}
</style>
<body>
<div id="outer">
<ul id="imgList">
<li><img src="../images/ad1.jpg" alt=""></li>
<li><img src="../images/ad2.jpg" alt=""></li>
<li><img src="../images/ad3.jpg" alt=""></li>
<li><img src="../images/ad4.jpg" alt=""></li>
<li><img src="../images/ad1.jpg" alt=""></li>
</ul>
<div id="navDiv">
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
</div>
</div>
</body>
<script>
window.onload = function () {
var imglist = document.getElementById("imgList");
var imgArr = document.getElementsByTagName('img');
//动态计算ul的长度
imglist.style.width = 690 * imgArr.length + 'px'
//默认显示图片的索引
var index = 0;
var allA = document.getElementsByTagName("a");
//点击超链接切换到指定的图片
for (let i = 0; i < allA.length; i++) {
allA[i].onclick = function () {
clearInterval(timer);
index = i;
imglist.style.left = "-" + i * 690 + "px"
setA(i);
autoChange();
}
}
var timer;
autoChange();
function autoChange() {
timer = setInterval(function () {
// if (index == allA.length - 1) {
// index = 0
// } else {
// index++;
// }
index++;
index %= imgArr.length;
imglist.style.left = "-" + index * 690 + "px"
setA(index)
}, 2000)
}
allA[index].style.backgroundColor = "black"
function setA(index) {
console.log(index, imgArr.length)
if (index >= imgArr.length - 1) {
index = 0;
imglist.style.left = 0;
}
for (let i = 0; i < allA.length; i++) {
allA[i].style.backgroundColor = "";
}
allA[index].style.backgroundColor = "black"
}
}
</script>
</html>
参考B站 https://www.bilibili.com/video/BV1YW411T7GX?p=137&spm_id_from=pageDriver
中封装好的tool.js方法