圖片輪播--基於JS陣列實現
阿新 • • 發佈:2019-01-04
之前釋出過一款js圖片輪播,是利用js調整margin來實現的輪播,程式碼、思路、邏輯比較複雜,今天介紹一款相當簡單的圖片輪播–基於JS陣列實現。
設計思路:
定義一個數組mypic,用於存放三張圖片地址,mypic[0]是第一張圖片的地址,mypic[1]是第二張圖片的地址,mypic[2]是第三張圖片的地址。利用JS獲取到的節點改變其src=mypic[i],做到圖片變換。
js程式碼:
window.onload=initLinks;
var mypic=new Array("tplb2/t1.jpg","tplb2/t2.jpg","tplb2/t3.jpg");
//定義陣列來存放圖片地址
var thispic=0;
function initLinks(){
document.getElementById('befLink').onclick=turnBef;
document.getElementById('nexLink').onclick=turnNex;
}
function turnBef(){
if(thispic==0){
thispic=mypic.length;
}
thispic--;
document.getElementById('tplbimg' ).src=mypic[thispic];
return false;
}
function turnNex(){
thispic++;
if(thispic==mypic.length){
thispic=0;
}
document.getElementById('tplbimg').src=mypic[thispic];
return false;
}
html:
<div class="tplb">
<img src="tplb2/t1.jpg" id="tplbimg" alt="" width="500" height="300">
<input type="button" id="befLink" value="上一張">
<input type="button" id="nexLink" value="下一張">
</div>
效果: