js新手。若是有錯誤,請指出,請原諒。
``
// 數組
<body>url
<div> <img src="picture/俄羅斯.jpg"> </div> <div onmouseover="stop()" onmouseout="star()"> <span>左箭頭</span> </div> <div onmouseover="stop()" onmouseout="star()"> <span>右箭頭</span> </div>
</body>spa
// 4.21 // 將全部URL放入一個數組,將index的值設置爲0 var imgs = ["picture/俄羅斯.jpg","picture/加拿大楓葉.jpg","picture/澳大利亞.jpg","picture/澳大利亞2.jpg","picture/加拿大楓葉.jpg","picture/澳大利亞.jpg"]; var index = 0; var stopValue = 0; var startValue = 0; // 獲取img的src屬性值,經過對index進行加1,將對應的數組元素設置爲img的src屬性。 function carousel(){ var img = document.getElementsByTagName("img")[0] if (index < imgs.length-1) { index++; img.setAttribute("src",imgs[index]); } else { // 當index值變成5,進入循環時,將img的src屬性設置爲第一個url地址,同時index值變爲0 img.setAttribute("src","picture/俄羅斯.jpg") index = 0; } } // 4.22 鼠標進入stop,鼠標離開start功能. //鼠標移動到箭頭所在的元素清楚定時器,鼠標離開則恢復輪播 // 定義兩個全局變量stopValue 和startValue 爲0; // onmouseover和onmouseout從進入對應的元素範圍到離開對應的元素範圍會執行不少次, // 經過兩個全局全局變量,讓它無論在對應的元素範圍內如何移動都只執行一次, // 避免setInterval時間出錯。 function stop(){ stopValue+=1; if(stopValue < 2){ clear(); // 當第一次onmouseover和onmouseout事件完成以後,全局變量的值改變, // 經過將兩個全局變量的值歸零,保證以後的onmouseover和onmouseout能執行。 startValue = 0 }
};code
function start(){ startValue+=1; if(startValue < 2){ setInt() // 同上。 stopValue = 0; } }; function clear() { clearInterval(int) }; function setInt(){ // 定時器被clearInterval取消後,須要從新設置定時器。 int = setInterval("carousel()",1000) }; // 利用定時器開始輪播 var int= setInterval("carousel()",1000)