<!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>轮播图</title>
<link rel="stylesheet" href="reset.css" />
<style>
#banner {
position: relative;
width: 700px;
height: 300px;
overflow: hidden;
}
#banner > .imgs {
width: 100%;
height: 100%;
/* display: flex; */
position: relative;
top: -100%;
transition: 0.3s;
}
#banner > .imgs > img {
width: 100%;
height: 100%;
}
#banner > .btns {
position: absolute;
top: 50%;
right: 0;
transform: translateY(-50%);
height: 100%;
/* width: 100%; */
display: flex;
flex-direction: column;
justify-content: space-around;
/* justify-content: space-between; */
}
#banner > .dian {
position: absolute;
top: 50%;
/* left: 50%; */
right: 10px;
transform: translateY(-50%);
/* display: flex; */
}
#banner > .dian > li {
width: 12px;
height: 12px;
background-color: #fff;
border-radius: 50%;
margin: 3px;
}
#banner > .dian > li.active {
background-color: #0aa1ed;
}
</style>
</head>
<body>
<div id="banner">
<div class="imgs">
<img src="./img/banner1.png" alt="" />
<img src="./img/banner2.png" alt="" />
<img src="./img/banner3.png" alt="" />
<img src="./img/banner4.png" alt="" />
</div>
<div class="btns">
<button class="prev">上一个</button>
<button class="next">下一个</button>
</div>
<ul class="dian">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
const lis = document.querySelectorAll("#banner>.dian>li");
const imgs = document.querySelector("#banner .imgs");
let active_index = 0;
console.log(lis);
lis.forEach((li, index) => {
li.onmouseover = function () {
lis.forEach(li => li.classList.remove("active"));
this.classList.add("active");
active_index = index;
console.log("index:", index); //0 1 2 3
imgs.style.top = `-${index}00%`;
};
});
// 下一个
const btn_next = document.querySelector(".btns .next");
btn_next.onclick = function () {
const next_index = (active_index + 1) % lis.length;
lis[next_index].onmouseover();
};
// 上一个
const btn_prev = document.querySelector(".btns .prev");
btn_prev.onclick = function () {
const prev_index = active_index ? active_index - 1 : lis.length - 1;
lis[prev_index].onmouseover();
};
// 自动滚动: 每隔3秒, 就自动触发一次 下一个 按钮的点击效果
setInterval(() => {
btn_next.onclick();
}, 3000);
</script>
</body>
</html>
该操作用的是 定位 的方式实现