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://www.cgvv.com.cn/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. python中scrapy處理項目數(shù)據(jù)的實例分析2. Python中讀取文件名中的數(shù)字的實例詳解3. 在idea中為注釋標(biāo)記作者日期操作4. 通過Ajax方式綁定select選項數(shù)據(jù)的實例5. JSP頁面的靜態(tài)包含和動態(tài)包含使用方法6. ASP.Net Core對USB攝像頭進行截圖7. ASP.NET MVC使用Boostrap實現(xiàn)產(chǎn)品展示、查詢、排序、分頁8. .net如何優(yōu)雅的使用EFCore實例詳解9. 使用AJAX(包含正則表達式)驗證用戶登錄的步驟10. ajax動態(tài)加載json數(shù)據(jù)并詳細解析
