1. <!DOCTYPE html>
    2. <html lang="zh">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>图片切换练习</title>
    8. <style>
    9. *{
    10. padding:0;
    11. margin:0;
    12. }
    13. #outer{
    14. width:1200px;
    15. height:790px;
    16. margin:0 auto;
    17. text-align:center;
    18. /* overflow:hidden; */
    19. /* padding:50px; */
    20. /* background-color:aquamarine; */
    21. }
    22. #outer > img{
    23. width:100%;
    24. }
    25. </style>
    26. <script>
    27. window.onload = function(){
    28. // 创建一个数组,用来保存图片的路径
    29. var imgArr = ["./img/01.jpg","./img/02.jpg","./img/03.jpg","./img/04.jpg","./img/05.jpg","./img/06.jpg"];
    30. var index = 0;
    31. var prev = document.getElementById("prev");
    32. // 要切换图片就是修改 img 标签的 src 属性
    33. var img = document.getElementsByTagName("img")[0];
    34. var info = document.getElementById("info");
    35. info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
    36. prev.onclick = function(){
    37. // 修改图片路径
    38. // img.src = "./img/02.jpg";
    39. // 切换上一张,索引自减
    40. index--;
    41. // 判断索引是否小于0
    42. if(index < 0){
    43. index = imgArr.length -1;
    44. }
    45. img.src = imgArr[index];
    46. info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
    47. };
    48. var next = document.getElementById("next");
    49. next.onclick = function(){
    50. // img.src = "./img/01.jpg";
    51. // 切换下一张,索引自增
    52. index++;
    53. if(index > imgArr.length-1){
    54. index = 0;
    55. }
    56. img.src = imgArr[index];
    57. info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
    58. // 0 - 5
    59. // 3 > 6-1
    60. };
    61. };
    62. </script>
    63. </head>
    64. <body>
    65. <div id="outer">
    66. <p id="info"></p>
    67. <img src="./img/01.jpg" alt="图片">
    68. <!-- <img src="./img/02.jpg" alt="图片">
    69. <img src="./img/03.jpg" alt="图片">
    70. <img src="./img/04.jpg" alt="图片">
    71. <img src="./img/05.jpg" alt="图片">
    72. <img src="./img/06.jpg" alt="图片"> -->
    73. <button id="prev">上一张</button>
    74. <button id="next">下一张</button>
    75. </div>
    76. </body>
    77. </html>

    自己试着做一做吧!😀