JS图片上下切换
_GotoWorld 人气:0源代码:
<!DOCTYPE html> <html lang="en"> <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>Document</title> <style type="text/css"> *{ margin: 0; padding: 0; } #outer{ width: 130px; margin: 50px auto; padding: 10px; background-color: greenyellow; text-align: center; } </style> <script type="text/javascript"> window.onload=function(){ var prev=document.getElementById("prev"); var next=document.getElementById("next"); //切换图片就是修改img的src属性 //获取img标签 var img=document.getElementsByTagName("img")[0]; //创建数组,保存图片路径 var imgArr=["1.png","2.png","3.png"]; //创建变量保存当前显示图片的索引 var index=0; //设置提示文字 var info=document.getElementById("info"); info.innerHTML="一共"+imgArr.length+"张图片,当前第"+(index+1)+"张"; prev.onclick=function(){ index--; //判断index是否小于0 if (index<0){ index=imgArr.length-1; } img.src=imgArr[index]; info.innerHTML="一共"+imgArr.length+"张图片,当前第"+(index+1)+"张"; }; next.onclick=function(){ index++; if(index>imgArr.length-1){ index=0; } img.src=imgArr[index]; info.innerHTML="一共"+imgArr.length+"张图片,当前第"+(index+1)+"张"; }; }; </script> </head> <body> <div id="outer"> <p id="info"></p> <img src="1.png" alt="1"> <button id="prev">上一张</button> <button id="next">下一张</button> </div> </body> </html>
效果如下图
加载全部内容