<!DOCTYPE html>
<html lang="zh">
<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>
<style>
*{
padding:0;
margin:0;
}
#outer{
width:1200px;
height:790px;
margin:0 auto;
text-align:center;
/* overflow:hidden; */
/* padding:50px; */
/* background-color:aquamarine; */
}
#outer > img{
width:100%;
}
</style>
<script>
window.onload = function(){
// 创建一个数组,用来保存图片的路径
var imgArr = ["./img/01.jpg","./img/02.jpg","./img/03.jpg","./img/04.jpg","./img/05.jpg","./img/06.jpg"];
var index = 0;
var prev = document.getElementById("prev");
// 要切换图片就是修改 img 标签的 src 属性
var img = document.getElementsByTagName("img")[0];
var info = document.getElementById("info");
info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
prev.onclick = function(){
// 修改图片路径
// img.src = "./img/02.jpg";
// 切换上一张,索引自减
index--;
// 判断索引是否小于0
if(index < 0){
index = imgArr.length -1;
}
img.src = imgArr[index];
info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
};
var next = document.getElementById("next");
next.onclick = function(){
// img.src = "./img/01.jpg";
// 切换下一张,索引自增
index++;
if(index > imgArr.length-1){
index = 0;
}
img.src = imgArr[index];
info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
// 0 - 5
// 3 > 6-1
};
};
</script>
</head>
<body>
<div id="outer">
<p id="info"></p>
<img src="./img/01.jpg" alt="图片">
<!-- <img src="./img/02.jpg" alt="图片">
<img src="./img/03.jpg" alt="图片">
<img src="./img/04.jpg" alt="图片">
<img src="./img/05.jpg" alt="图片">
<img src="./img/06.jpg" alt="图片"> -->
<button id="prev">上一张</button>
<button id="next">下一张</button>
</div>
</body>
</html>
自己试着做一做吧!😀