<div id="photo">
<p id="p"></p>
<img src="./image/01.jpg" alt="">//图片存储路径
<div class="btn">
<button id="prev">上一张</button>
<button id="next">下一张</button>
</div>
</div>
css部分:
#p {
margin: 0;
color: white;
padding: 5px;
}
#photo {
width: 360px;
height: 360px;
margin: 50px auto;
text-align: center;
background-color: skyblue;
padding: 10px;
}
img {
width: 300px;
height: 300px;
}
.btn {
width: 350px;
height: 25px;
justify-content: space-around;
display: flex;
}
js代码:
window.onload = function () {
var arr = ["./image/01.jpg", "./image/02.jpg", "./image/03.jpg", "./image/04.jpg", "./image/05.jpg", "./image/06.jpg"];
var index = 0;
var text = document.getElementById("p");
text.innerHTML = "一共有" + arr.length + "张图片," + "现在是第" + (index + 1) + "张"
var prev = document.getElementById("prev");
var next = document.getElementById("next");
var img = document.getElementsByTagName("img")[0];
prev.onclick = function () {
if (index == 0) {
index = arr.length;
}
index--
img.src = arr[index]
text.innerHTML = "一共有" + arr.length + "张图片," + "现在是第" + (index + 1) + "张"
}
next.onclick = function () {
if (index == arr.length - 1) {
index = -1;
}
index++
img.src = arr[index]
text.innerHTML = "一共有" + arr.length + "张图片," + "现在是第" + (index + 1) + "张"
}
}
呈现效果:
全部代码:
<!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>
<style>
#p {
margin: 0;
color: white;
padding: 5px;
}
#photo {
width: 360px;
height: 360px;
margin: 50px auto;
text-align: center;
background-color: skyblue;
padding: 10px;
}
img {
width: 300px;
height: 300px;
}
.btn {
width: 350px;
height: 25px;
justify-content: space-around;
display: flex;
}
</style>
</head>
<body>
<script>
window.onload = function () {
var arr = ["./image/01.jpg", "./image/02.jpg", "./image/03.jpg", "./image/04.jpg", "./image/05.jpg", "./image/06.jpg"];
var index = 0;
var text = document.getElementById("p");
text.innerHTML = "一共有" + arr.length + "张图片," + "现在是第" + (index + 1) + "张"
var prev = document.getElementById("prev");
var next = document.getElementById("next");
var img = document.getElementsByTagName("img")[0];
prev.onclick = function () {
if (index == 0) {
index = arr.length;
}
index--
img.src = arr[index]
text.innerHTML = "一共有" + arr.length + "张图片," + "现在是第" + (index + 1) + "张"
}
next.onclick = function () {
if (index == arr.length - 1) {
index = -1;
}
index++
img.src = arr[index]
text.innerHTML = "一共有" + arr.length + "张图片," + "现在是第" + (index + 1) + "张"
}
}
</script>
<div id="photo">
<p id="p"></p>
<img src="./image/01.jpg" alt="">
<div class="btn">
<button id="prev">上一张</button>
<button id="next">下一张</button>
</div>
</div>
</body>
</html>