春天到了,各种绚丽的花朵都开放了,金黄的油菜花,成了蝴蝶的天地,美丽的蝴蝶在金黄色的舞台上跳着柔和而优美的舞姿。它们一会儿在空中飞舞,一会儿静静地停留在油菜花上。给春天增添了不少乐趣。油菜花的美丽,同时也吸引了不少 "劳动人民 "——蜜蜂,它们总是不分昼夜地不辞辛劳地给油菜花授粉。偶尔一阵微风吹来,金黄的油菜花立刻涌起了高低起伏的 "金浪花 "。远远望去,真是美不胜收!
代码如下所示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片切换</title> <style> *{ margin: 0; padding: 0; } .box{ width: 200px; height: 300px; margin: 50px auto; padding: 20px; background-color: skyblue; text-align: center; } img{ width: 200px; height: 200px; margin: 20px 0; } </style> <script> // 存储照片地址的数组 let imgArr = ["https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051704animal1.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051711animal2.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051717animal3.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051722animal4.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051726animal5.png"]; // 照片的索引 let index = 0; window.onload = function() { let oP = document.getElementsByTagName("p")[0]; oP.innerHTML = "一共有" + imgArr.length + "张照片,这是第" + (index+1) +"张"; let oImg = document.getElementsByTagName("img")[0]; let oPrev = document.getElementsByClassName("prev")[0]; let oNext = document.getElementsByClassName("next")[0]; // 点击上一张响应事件 oPrev.onclick = function () { index--; //实现照片循环 if (index < 0) { index = imgArr.length-1; } oP.innerHTML = "一共有" + imgArr.length + "张照片,这是第" + (index+1) +"张"; oImg.src = imgArr[index]; }; // 点击下一张响应事件 oNext.onclick = function () { index++; //实现照片循环 if (index >= imgArr.length) { index = 0; } oP.innerHTML = "一共有" + imgArr.length + "张照片,这是第" + (index+1) +"张"; oImg.src = imgArr[index]; }; }; </script> </head> <body> <div class="box"> <p></p> <img src="../../images/animal1.png" alt=""> <button class="prev">上一张</button> <button class="next">下一张</button> </div> </body> </html>
最终的效果
总结
到此这篇关于JavaScript实现简单的图片切换功能(实例代码)的文章就介绍到这了,更多相关js 图片切换内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!