function Slider(id){ //屬性 // 1. 通過id獲取元素對象(大盒子) this.bigBox = document.getElementById(id); //2. 獲取出大盒子中的所有圖片(數組) this.ullis = this.bigBox.children[0]. ...
function Slider(id){ //屬性 // 1. 通過id獲取元素對象(大盒子) this.bigBox = document.getElementById(id); //2. 獲取出大盒子中的所有圖片(數組) this.ullis = this.bigBox.children[0].children; //3. 統計圖片數量(數組.length) this.num = this.ullis.length; //4. 獲取所有的小圓點 this.ollis = this.createElement(); //5. 設置輪播的當前下標 this.indexA = 0; //8. 獲取文字信息的div this.div = $id('msg'); this.slide(); //6. 獲取左按鈕 this.ltBtn = $id('ltBtn'); //7. 獲取右按鈕 this.rtBtn = $id('rtBtn'); this.addEvent(); //9. 計時器 this.timer = null; this.autoPlay(); } Slider.prototype.createElement = function(){ //1. 左按鈕 var spanleft = document.createElement('span'); spanleft.id = 'ltBtn'; spanleft.innerHTML = '<'; this.bigBox.appendChild(spanleft); //2. 右按鈕 var spanright = document.createElement('span'); spanright.id = 'rtBtn'; spanright.innerHTML = '>'; this.bigBox.appendChild(spanright); //3. ol li var arr = []; //放置li //創建ol var ol = document.createElement('ol'); //創建li for(var i = 0;i < this.num;i ++){ var li = document.createElement('li'); arr.push(li); ol.appendChild(li); } this.bigBox.appendChild(ol); //4. 信息框(div) var div = document.createElement('div'); div.id = 'msg'; this.bigBox.appendChild(div); return arr; } Slider.prototype.slide = function(){ //1》圖片輪播 // 遍歷所有的圖片,display - none for(var i = 0;i < this.num;i ++){ this.ullis[i].style.display = 'none'; } // 當前圖片 display-block this.ullis[this.indexA].style.display = 'block'; //2》 小圓點 //遍歷所有的小圓點,background=red for(var i = 0;i < this.num;i ++){ this.ollis[i].style.backgroundColor = 'red'; } //當前小圓點,background = blue this.ollis[this.indexA].style.backgroundColor = 'blue'; //信息框 = img中的alt屬性 this.div.innerHTML = this.ullis[this.indexA].firstElementChild.firstElementChild.alt; } Slider.prototype.addEvent = function(){ var that = this; // 1. 左按鈕 -- 點擊事件-- 改變當前下標的值,調用輪播方法 this.ltBtn.onclick = function(){ that.indexA --; if(that.indexA == -1){ that.indexA = that.num - 1; } that.slide(); } //2. 右按鈕 -- 點擊事件--改變當前下標的值,調用輪播方法 this.rtBtn.onclick = function(){ that.indexA ++; if(that.indexA === that.num){ that.indexA = 0; } that.slide(); } //3. 遍歷小圓點--移入事件--改變當前下標 的值,調用輪播方法 for(var i = 0;i < this.num;i ++){ //記錄下標 this.ollis[i].index = i; this.ollis[i].onmouseenter = function(){ that.indexA = this.index; that.slide(); } } } Slider.prototype.autoPlay = function(){ var that = this; this.timer = setInterval(function(){ that.indexA ++; if(that.indexA === that.num){ that.indexA = 0; } that.slide(); },3000) //移入大盒子,停止自動輪播 this.bigBox.onmouseenter = function(){ clearInterval(that.timer); } //移出大盒子,開啟自動輪播 this.bigBox.onmouseleave = function(){ that.autoPlay(); } } //工具箱 function $id(id){ return document.getElementById(id); }