效果图:
代码展示:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>图片切换</title>
<style>
.container {
position: relative;
}
.container>img {
width: 100%;
heignt: 300px;
display: none;
position: absolute;
}
._button {
width: 100%;
height: 50px;
top: 220px;
position: absolute;
}
._button>#_but_1 {
width: 10px;
height: 50px;
text-indent: -3px;
float: left;
opacity: 0.5;
}
._button>#_but_2 {
width: 10px;
height: 50px;
text-indent: -3px;
float: right;
opacity: 0.5;
}
</style>
<script>
window.onload = (event) => {
let img_arr = document.querySelectorAll(".container > img")
let left_click = document.getElementById("_but_1")
let right_click = document.getElementById("_but_2")
let index = 0
let timer = setInterval(change,1500) /* 开启定时器循环 */
function change() {
img_arr[index].style.display = "none"
index = ++index % img_arr.length
img_arr[index].style.display = "block"
}
left_click.onclick = (e) => {
clearInterval(timer) /* 点击之后取消定时器 */
img_arr[index].style.display = "none"
if (index == 0){ /* 低于最小的图片索引时,回到最大的图片索引 */
index = img_arr.length - 1
}
else{
index = --index
}
img_arr[index].style.display = "block"
}
right_click.onclick = (e) => {
clearInterval(timer)
img_arr[index].style.display = "none"
index = ++index % img_arr.length
img_arr[index].style.display = "block"
}
}
</script>
</head>
<body>
<div class="container">
<img src="./img/图1.jpg" alt="">
<img src="./img/图2.jpg" alt="">
<img src="./img/图3.jpg" alt="">
<div class="_button">
<button id="_but_1"><</button>
<button id="_but_2">></button>
</div>
</div>
</body>
</html>