JavaScript實現(xiàn)簡單的圖片切換功能(實例代碼)
代碼如下所示:
<!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> // 存儲照片地址的數(shù)組 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]; // 點擊上一張響應(yīng)事件 oPrev.onclick = function () {index--;//實現(xiàn)照片循環(huán)if (index < 0) { index = imgArr.length-1;}oP.innerHTML = '一共有' + imgArr.length + '張照片,這是第' + (index+1) +'張';oImg.src = imgArr[index]; }; // 點擊下一張響應(yīng)事件 oNext.onclick = function () {index++;//實現(xiàn)照片循環(huán)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='http://m.b3g6.com/images/animal1.png' alt=''> <button class='prev'>上一張</button> <button class='next'>下一張</button> </div></body></html>
最終的效果

總結(jié)
到此這篇關(guān)于JavaScript實現(xiàn)簡單的圖片切換功能(實例代碼)的文章就介紹到這了,更多相關(guān)js 圖片切換內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. SpringBoot整合Redis的步驟2. Properties 持久的屬性集的實例詳解3. IntelliJ IDEA 2020最新激活碼(親測有效,可激活至 2089 年)4. 基于python調(diào)用jenkins-cli實現(xiàn)快速發(fā)布5. ASP.NET MVC實現(xiàn)區(qū)域或城市選擇6. ASP.NET MVC實現(xiàn)本地化和全球化7. python 網(wǎng)頁解析器掌握第三方 lxml 擴展庫與 xpath 的使用方法8. Python使用xlrd實現(xiàn)讀取合并單元格9. React中使用TS完成父組件調(diào)用子組件的操作方法10. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進度條

網(wǎng)公網(wǎng)安備