首先要注意的是,在HTML里写js的时候,所有的js的内容都要在window.onload=function(){}中
2.设置按钮并且要在js内部进行获取
3.在html里面设置img标签,在js里获取img,并设置img的容器,将需要切换的img图片放在容器中
4.使用onclick属性,使在点击按钮的时候实现照片的切换,这个function的内容就是就是imgArr[index];
<script type="text/javascript">
/*
*实现点击按钮切换
*/
window.onload = function() { //确保整个事件在页面加载完成之后执行
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var img = document.getElementsByTagName("img")[0];
var imgArr = ["img/d4a5a51676c1f82855d63a4fc0b069ed.jpg ",
"img/83610107838ee51e9eb29685ba9b44b6.jpg ",
"img/e52c3e98602b90f198ec316dce253cba.jpg ",
"img/972fe1db817a46fc5c461337bf94d20f.jpg ",
];
var index = 0;
var info = document.getElementsByName("info");
btn1.onclick = function() {
index--;
if (index < 0) {
index = imgArr.length - 1;
}
info.innerHTML = "一共有" + index + "张,现在是第" + (index + 1) + "张";
img.src = imgArr[index];
}
btn2.onclick = function() {
index++;
if (index > imgArr.length - 1) {
index = 0;
}
info.innerHTML = "一共有" + index + "张,现在是第" + (index + 1) + "张";
img.src = imgArr[index];
}
};
</script>
<style>
* {
margin: 0px;
padding: 0px;
}
.pic {
width: 2450px;
height: 1000px;
margin: 100px auto;
padding: 30px;
background-color: seagreen;
overflow: hidden;
}
button {
width: 200px;
text-align: center;
}
</style>
</head>
<body>
<div class="pic">
<p class="info"></p>
<img src="img/d4a5a51676c1f82855d63a4fc0b069ed.jpg " alt="可乐">
<button id="btn1">上一张</button>
<button id="btn2">下一张</button>
</div>
</body>