在團隊帶人,突然被人問到輪播圖如何實現,進入前端領域有一年多了,但很久沒自己寫過,一直是用大牛寫的插件,今天就寫個簡單的適合入門者學習的小教程。當然,輪播圖的實現原理與設計模式有很多種,我這里講的是用面向過程函數式編程去實現,相對於面向對象設計模式,代碼難免會顯得臃腫冗余。但沒有面向對象的抽象卻很適合新手理解與學習。已經在BAT的同學看到希望少噴點。另外可以多提意見。
輪播圖的原理:
一系列的大小相等的圖片平鋪,利用CSS布局只顯示一張圖片,其余隱藏。通過計算偏移量利用定時器實現自動播放,或通過手動點擊事件切換圖片。
Html布局
首先父容器container存放所有內容,子容器list存在圖片。子容器buttons存放按鈕小圓點。
1 <div id="container"> 2 <div id="list" style="left: -600px;"> 3 <img src="img/5.jpg" alt="1" /> 4 <img src="img/1.jpg" alt="1" /> 5 <img src="img/2.jpg" alt="2" /> 6 <img src="img/3.jpg" alt="3" /> 7 <img src="img/4.jpg" alt="4" /> 8 <img src="img/5.jpg" alt="5" /> 9 <img src="img/1.jpg" alt="5" /> 10 </div> 11 <div id="buttons"> 12 <span index="1" class="on"></span> 13 <span index="2"></span> 14 <span index="3"></span> 15 <span index="4"></span> 16 <span index="5"></span> 17 </div> 18 <a href="javascript:;" id="prev" class="arrow"><</a> 19 <a href="javascript:;" id="next" class="arrow">></a> 20 </div>
優化,無縫滾動。
當你從最后一張圖切換回第一張圖時,有很大空白,利用兩張輔助圖來填補這個空白。
這里補充下無縫滾動,直接看代碼,復制最后一張圖片放置第一張圖片前,同時復制第一張圖片放置最后一張圖片的后面。並且,將第一張圖片輔助圖(實際上是實際顯示的第5張圖片隱藏起來,故設置style="left: -600px;")
CSS修飾
1、對盒子模型,文檔流的理解,絕對定位問題。
2、注意list的overflow:hidden;只顯示窗口的一張圖片,把左右兩邊的都隱藏起來。
3、確保buttons中每個span所在層置頂,將其設置為最頂端。(z-index:999)我這里設置為z-index:2
* { margin: 0; padding: 0; text-decoration: none; } body { padding: 20px; } #container { position: relative; width: 600px; height: 400px; border: 3px solid #333; overflow: hidden; } #list { position: absolute; z-index: 1; width: 4200px; height: 400px; } #list img { float: left; width: 600px; height: 400px; } #buttons { position: absolute; left: 250px; bottom: 20px; z-index: 2; height: 10px; width: 100px; } #buttons span { float: left; margin-right: 5px; width: 10px; height: 10px; border: 1px solid #fff; border-radius: 50%; background: #333; cursor: pointer; } #buttons .on { background: orangered; } .arrow { position: absolute; top: 180px; z-index: 2; display: none; width: 40px; height: 40px; font-size: 36px; font-weight: bold; line-height: 39px; text-align: center; color: #fff; background-color: RGBA(0, 0, 0, .3); cursor: pointer; } .arrow:hover { background-color: RGBA(0, 0, 0, .7); } #container:hover .arrow { display: block; } #prev { left: 20px; } #next { right: 20px; }
Js
首先我們先實現出手動點擊左右兩個箭頭切換圖片的效果:
window.onload = function() { var list = document.getElementById('list');var prev = document.getElementById('prev'); var next = document.getElementById('next'); function animate(offset) { //獲取的是style.left,是相對左邊獲取距離,所以第一張圖后style.left都為負值, //且style.left獲取的是字符串,需要用parseInt()取整轉化為數字。 var newLeft = parseInt(list.style.left) + offset; list.style.left = newLeft + 'px'; } prev.onclick = function() { animate(600); } next.onclick = function() { animate(-600); } }
運行后我們會發現,一直點擊右箭頭 ,會出現空白,而且,不能回到第一張圖片。要點擊左箭頭才能回到第一張圖片。
利用谷歌瀏覽器F12,原因是我們利用偏移量left來獲取圖片,當看到left值小於3600時,因為沒有第8張圖片就出現空白,所以這里我們需要對偏移量做一個判斷。
在animate函數里加上這么一段:
if(newLeft<-3000){ list.style.left = -600 + 'px'; } if(newLeft>-600){ list.style.left = -3000 + 'px'; }
好,運行一下,沒問題了。輪播圖,顧名思義,是自己會動的圖片,這個時候我們需要用到瀏覽器的內置對象定時器。
對於定時器,有必要說明一下setInterval()跟setTimeout的區別了。簡單來說,setInterval()執行多次,setTimeout()只執行一次。
更具體的用法可以點擊鏈接查看區別:window.setInterval window.setTimeout 。
這里我們是用setInterval(),因為我們的圖片需要循環滾動。插入下面
var timer; function play() { timer = setInterval(function () { prev.onclick() }, 1500) } play();
運行,ok!
但是,當我們想仔細看某一張圖片時候,要把圖片停住,我們清楚定時器就可以了,這里用到window.clearInterval 這個方法。
這里,我們需要對其DOM操作,需要獲取整個輪播圖區域;
var container = document.getElementById('container'); function stop() { clearInterval(timer); } container.onmouseover = stop; container.onmouseout = play;
但這里,一個輪播圖基本算完成了,有同學·會問,那么簡單。看到圖片下面的那一排小圓點沒。我給你加功能了。
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
這里是升級版:
var buttons = document.getElementById('buttons').getElementsByTagName('span'); var index = 1; function buttonsShow() { //這里需要清除之前的樣式 for (var i = 0; i < buttons.length; i++) { if (buttons[i].className == 'on') { buttons[i].className = ''; } } //數組從0開始,故index需要-1 buttons[index - 1].className = 'on'; } prev.onclick = function() { index -= 1; if (index < 1) { index = 5; } buttonsShow(); animate(600); } next.onclick = function() { //由於上邊定時器的作用,index會一直遞增下去,我們只有5個小圓點,所以需要做出判斷 index += 1; if (index > 5) { index = 1; } buttonsShow(); animate(-600); }
現在看起來正常多了吧,但我們想實現通過鼠標任意點擊其中一個小圓點,切換到相應的圖片,原理同樣,我們還是需要通過偏移量去找到對應的圖片。
for (var i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { // 在瀏覽器的控制台打印一下,看看結果 console.log(i); /* 偏移量獲取:這里獲得鼠標移動到小圓點的位置,用this把index綁定到對象buttons[i]上,去谷歌this的用法 */ /* 由於這里的index是自定義屬性,需要用到getAttribute()這個DOM2級方法,去獲取自定義index的屬性*/ var clickIndex = parseInt(this.getAttribute('index')); var offset = 600 * (index - clickIndex); animate(offset); //存放鼠標點擊后的位置,用於小圓點的正常顯示 index = clickIndex; buttonsShow(); } }
到這一步時,以為大功告成?你在控制台會發現打印出來的永遠的是i=5。
錯誤原因:沒有正確獲取i值,使用閉包就可以了。你在高級程序設計第三版中76頁,會看到這么一句話:
“對javascript來說,由for語句創建的變量i即使在for循環執行結束后,也依舊會存在於循環外部的執行環境中。”
就是說,js沒有塊級作用域這東西,(可能我C寫多了,混淆了)。在第一次循環(從 i=0 到 4 這一過程)結束后,最后的 i 獲取到的為 buttons.length 的值被
保存在for循環之外,最后鼠標點擊任何一個小圓點時,自然訪問的一直是 i=5 了。
正確代碼如下:
for (var i = 0; i < buttons.length; i++) { // 這里使用的是立即執行函數, (function(i) { buttons[i].onclick = function() { var clickIndex = parseInt(this.getAttribute('index')); var offset = 600 * (index - clickIndex); animate(offset); index = clickIndex; buttonsShow(); } })(i) }
有關閉包的知識我不展開來說,要說的又一大推,
大家可以參考下我很久之前的博客: 頭疼的閉包
大家,可能發現了,這個輪播圖有點奇怪,不中規中矩,它是向左切換的,改寫一下:
function play() { //將輪播圖換成向右切換圖片 timer = setInterval(function () { next.onclick(); }, 2000) }

1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 <style type="text/css"> 8 * { 9 margin: 0; 10 padding: 0; 11 text-decoration: none; 12 } 13 14 body { 15 padding: 20px; 16 } 17 18 #container { 19 position: relative; 20 width: 600px; 21 height: 400px; 22 border: 3px solid #333; 23 overflow: hidden; 24 } 25 26 #list { 27 position: absolute; 28 z-index: 1; 29 width: 4200px; 30 height: 400px; 31 } 32 33 #list img { 34 float: left; 35 width: 600px; 36 height: 400px; 37 } 38 39 #buttons { 40 position: absolute; 41 left: 250px; 42 bottom: 20px; 43 z-index: 2; 44 height: 10px; 45 width: 100px; 46 } 47 48 #buttons span { 49 float: left; 50 margin-right: 5px; 51 width: 10px; 52 height: 10px; 53 border: 1px solid #fff; 54 border-radius: 50%; 55 background: #333; 56 cursor: pointer; 57 } 58 59 #buttons .on { 60 background: orangered; 61 } 62 63 .arrow { 64 position: absolute; 65 top: 180px; 66 z-index: 2; 67 display: none; 68 width: 40px; 69 height: 40px; 70 font-size: 36px; 71 font-weight: bold; 72 line-height: 39px; 73 text-align: center; 74 color: #fff; 75 background-color: RGBA(0, 0, 0, .3); 76 cursor: pointer; 77 } 78 79 .arrow:hover { 80 background-color: RGBA(0, 0, 0, .7); 81 } 82 83 #container:hover .arrow { 84 display: block; 85 } 86 87 #prev { 88 left: 20px; 89 } 90 91 #next { 92 right: 20px; 93 } 94 </style> 95 <script type="text/javascript"> 96 /* 知識點: */ 97 /* this用法 */ 98 /* DOM事件 */ 99 /* 定時器 */ 100 101 window.onload = function() { 102 var container = document.getElementById('container'); 103 var list = document.getElementById('list'); 104 var buttons = document.getElementById('buttons').getElementsByTagName('span'); 105 var prev = document.getElementById('prev'); 106 var next = document.getElementById('next'); 107 var index = 1; 108 var timer; 109 110 function animate(offset) { 111 //獲取的是style.left,是相對左邊獲取距離,所以第一張圖后style.left都為負值, 112 //且style.left獲取的是字符串,需要用parseInt()取整轉化為數字。 113 var newLeft = parseInt(list.style.left) + offset; 114 list.style.left = newLeft + 'px'; 115 //無限滾動判斷 116 if (newLeft > -600) { 117 list.style.left = -3000 + 'px'; 118 } 119 if (newLeft < -3000) { 120 list.style.left = -600 + 'px'; 121 } 122 } 123 124 function play() { 125 //重復執行的定時器 126 timer = setInterval(function() { 127 next.onclick(); 128 }, 2000) 129 } 130 131 function stop() { 132 clearInterval(timer); 133 } 134 135 function buttonsShow() { 136 //將之前的小圓點的樣式清除 137 for (var i = 0; i < buttons.length; i++) { 138 if (buttons[i].className == "on") { 139 buttons[i].className = ""; 140 } 141 } 142 //數組從0開始,故index需要-1 143 buttons[index - 1].className = "on"; 144 } 145 146 prev.onclick = function() { 147 index -= 1; 148 if (index < 1) { 149 index = 5 150 } 151 buttonsShow(); 152 animate(600); 153 }; 154 155 next.onclick = function() { 156 //由於上邊定時器的作用,index會一直遞增下去,我們只有5個小圓點,所以需要做出判斷 157 index += 1; 158 if (index > 5) { 159 index = 1 160 } 161 animate(-600); 162 buttonsShow(); 163 }; 164 165 for (var i = 0; i < buttons.length; i++) { 166 (function(i) { 167 buttons[i].onclick = function() { 168 169 /* 這里獲得鼠標移動到小圓點的位置,用this把index綁定到對象buttons[i]上,去谷歌this的用法 */ 170 /* 由於這里的index是自定義屬性,需要用到getAttribute()這個DOM2級方法,去獲取自定義index的屬性*/ 171 var clickIndex = parseInt(this.getAttribute('index')); 172 var offset = 600 * (index - clickIndex); //這個index是當前圖片停留時的index 173 animate(offset); 174 index = clickIndex; //存放鼠標點擊后的位置,用於小圓點的正常顯示 175 buttonsShow(); 176 } 177 })(i) 178 } 179 180 container.onmouseover = stop; 181 container.onmouseout = play; 182 play(); 183 184 } 185 </script> 186 </head> 187 188 <body> 189 190 <div id="container"> 191 <div id="list" style="left: -600px;"> 192 <img src="" alt="1" /> 193 <img src="" alt="1" /> 194 <img src="" alt="2" /> 195 <img src="" alt="3" /> 196 <img src="" alt="4" /> 197 <img src="" alt="5" /> 198 <img src="" alt="5" /> 199 </div> 200 <div id="buttons"> 201 <span index="1" class="on"></span> 202 <span index="2"></span> 203 <span index="3"></span> 204 <span index="4"></span> 205 <span index="5"></span> 206 </div> 207 <a href="javascript:;" id="prev" class="arrow"><</a> 208 <a href="javascript:;" id="next" class="arrow">></a> 209 </div> 210 211 </body> 212 213 </html>
這里結合評論,補充下:
就算是初學者也要特別注意代碼規范問題,上面的CSS實在太不規范了,難怪我帶的人都不怎樣,哈哈哈。。。
- Css的書寫順序
- CSS里最好不用或直接不用id來改變樣式(我這里是id為了方便DOM操作)
這里推薦css規范的技術文章
前端前輩的博客: http://www.cnblogs.com/hustskyking/p/css-spec.html
或者這位大神的Github:https://github.com/fex-team/styleguide/blob/master/css.md
以及KISSY v1.4 Documentation的css編碼規范: http://docs.kissyui.com/1.4/docs/html/tutorials/style-guide/css-coding-style.html
over
最后,我們完成了一個簡單的輪播圖,在我的 Github 里可以找到源碼。覺得不錯就star一下。