实现图片上一张和下一张的切换,带有提示项
HTML页面
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE-edge"> <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> <link rel="stylesheet" href="/cssDocument/test.css"> <script> window.onload = function () { //获取两个按钮 var prev = document.getElementById("prev"); var next = document.getElementById("next"); //获取img标签 var img = document.getElementsByTagName("img")[0]; var imgArr = ["/img/1.png", "/img/2.png", "/img/3.png", "/img/4.png", "/img/5.png"] var index = 0; //获取id为info的元素 var info=document.getElementById("info"); //设置提示文字 info.innerHTML="一共"+imgArr.length+"张图片,当前是第"+(index+1)+"张" //绑定点击响应函数 //上一张 prev.onclick = function () { index--; if (index < 0) { index = imgArr.length-1; } info.innerHTML="一共"+imgArr.length+"张图片,当前是第"+(index+1)+"张" img.src = imgArr[index]; }; //下一张 next.onclick = function () { index++; if (index > imgArr.length-1) { index = 0; } info.innerHTML="一共"+imgArr.length+"张图片,当前是第"+(index+1)+"张" img.src = imgArr[index]; }; }; </script> <title>图片切换</title> </head> <body> <!-- 图片摆放 --> <div class="outer"> <p id="info">一共5张图片,当前在第1张</p> <img src="/img/1.png" alt=""> <div class="imgButton"> <button id="prev">上一张</button> <button id="next">下一张</button> </div> </div> </body> </html>
css文件
/* 清除样式 */ *{ margin: 0; padding: 0; } /* 图片居中 */ .outer{ width: 100%; margin: 50px auto; padding: 10px; background-color: bisque; text-align: center; }
结果显示:到最后一张时,点击下一张会回到第一张
在第一张时,点击上一张会跳转到最后一张