JavaScript切换多张图片
循环切换图片
HTML+CSS+JavaScript
html部分
<body>
<div class="outer">
<p id="info"></p>
<img src="./images/banner1.png" alt="图片" title="图片">
<button id='prev'>上一张</button>
<button id='next'>下一张</button>
</div>
</body>
css部分
<style>
* {
padding: 0;
margin: 0;
}
.outer {
width: 1000px;
background-color: #bfa;
margin: 50px auto;
text-align: center;
padding: 10px;
}
img {
width: 900px;
display: block;
margin: 0 auto;
}
button {
margin: 5px;
}
</style>
JavaScript部分
这里用到了JavaScript的DOM对象
<script>
// 加载文档
window.onload = function () {
//获取img标签
var img = document.getElementsByTagName("img")[0];
//创建一个数组保存所有图片的路径
//这里设置图片文件的路径
var imgArr = ["./images/banner1.png", "./images/banner2.png", "./images/banner3.png", "./images/banner4.png", "./images/banner5.png"];
//设置图片初始值
var index = 0;
//获取id为info的p标签
var info = document.getElementById("info");
info.innerHTML = "一共" + imgArr.length + "张," + "当前为第" + (index + 1) + "张";
//绑定两个按钮
//上一张
document.getElementById("prev").onclick = function () {
index--;
//判断index是否小于0
if (index < 0) {
index = imgArr.length - 1;//循环(第一张-》最后一张)
}
img.src = imgArr[index];
info.innerHTML = "一共" + imgArr.length + "张," + "当前为第" + (index + 1) + "张";
};
//下一张
document.getElementById("next").onclick = function () {
index++;
//判断index是否大于数组的长度-1(数组的最大下标)
if (index > imgArr.length - 1) {
index = 0;//循环(最后一张-》第一张)
}
img.src = imgArr[index];
info.innerHTML = "一共" + imgArr.length + "张," + "当前为第" + (index + 1) + "张";
}
};
</script>
预览效果: