1.首先我们写个基本样式:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div img { width: 323px; border: pink solid 15px; } .outer { width: 353px; margin: 0 auto; } .outer .left { float: left; } .outer .right { float: right; } </style> </head> <body> <div class="outer"> <img id="img" src="img/1.jpg" alt="美女"> <button class="left">上一张</button> <button class="right">下一张</button> </div> </body> </html>
如图所示:
2.我们在img文件夹下面多放几张图片,然后把路径写入一个数组中,开始编写js代码
<script> window.onload = function (){ // 存放图片路径的数组 let src = ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg"]; // 访问下标 let i = 0; // 获取一组button let elementsByTagName = document.getElementsByTagName("button"); // 获取需要改变的图片地址 let elementById = document.getElementById("img"); // 遍历button元素 for (let elementsByTagNameElement of elementsByTagName) { elementsByTagNameElement.onclick =function () { if(elementsByTagNameElement.innerHTML === "上一张"){ // 防止下标为负数 if (i===0){ i=src.length-1; elementById.src = src[i] }else{ i--; elementById.src = src[i] } }if(elementsByTagNameElement.innerHTML==="下一张"){ // 防止下标越界 if(i === src.length-1){ i=0; elementById.src = src[i] }else{ i++; elementById.src=src[i]; } } } } } </script>
运行即可