将图片和文字放入一个div之中然后点击按钮就可以将图片和文字进行动态转变!
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function(){ var a = document.getElementById("a"); var buts = document.getElementById("b"); var butx = document.getElementById("c"); var imgarr = ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg","img/5.jpg","img/6.jpg","img/7.jpg","img/8.jpg","img/9.jpg"]; // 创建一个变量来保存当前正在显示的索引 var index = 0; var info = document.getElementById("info"); info.innerHTML = "一共"+imgarr.length+"当前"+(index+1)+"张"; buts.onclick = function(){ index--; if(index < 0){ index = imgarr.length-1; } a.src = imgarr[index]; info.innerHTML = "一共"+imgarr.length+"当前第"+(index+1)+"张"; } butx.onclick = function(){ index++; if(index > imgarr.length-1){ index = 0; } a.src = imgarr[index]; info.innerHTML = "一共"+imgarr.length+"当前第"+(index+1)+"张"; } } </script> <style> *{ margin: 0; padding: 0; } div{ 360px; margin:20px auto; text-align:center; padding:10px; background: brown; } </style> </head> <body> <div> <p id="info"></p> <img src="img/1.jpg" id="a"> <button id="b">buts上一张</button> <button id="c">butx下一张</button> </div> </body> </html>
页面效果: