在團隊帶人,忽然被人問到輪播圖如何實現,進入前端領域有一年多了,但好久沒本身寫過,一直是用大牛寫的插件,今天就寫個簡單的適合入門者學習的小教程。固然,輪播圖的實現原理與設計模式有不少種,我這裏講的是用面向過程函數式編程去實現,相對於面向對象設計模式,代碼不免會顯得臃腫冗餘。但沒有面向對象的抽象卻很適合新手理解與學習。已經在BAT的同窗看到但願少噴點。另外能夠多提意見。javascript
輪播圖的原理:css
一系列的大小相等的圖片平鋪,利用CSS佈局只顯示一張圖片,其他隱藏。經過計算偏移量利用定時器實現自動播放,或經過手動點擊事件切換圖片。html
Html佈局前端
首先父容器container存放全部內容,子容器list存在圖片。子容器buttons存放按鈕小圓點。java
<div id="container">
<div id="list" style="left: -600px;">
<img src="img/5.jpg" alt="1" />
<img src="img/1.jpg" alt="1" />
<img src="img/2.jpg" alt="2" />
<img src="img/3.jpg" alt="3" />
<img src="img/4.jpg" alt="4" />
<img src="img/5.jpg" alt="5" />
<img src="img/1.jpg" alt="5" />
</div>
<div id="buttons">
<span index="1" class="on"></span>
<span index="2"></span>
<span index="3"></span>
<span index="4"></span>
<span index="5"></span>
</div>
<a href="javascript:;" id="prev" class="arrow"><</a>
<a href="javascript:;" id="next" class="arrow">></a>
</div>git
優化,無縫滾動。github
當你從最後一張圖切換回第一張圖時,有很大空白,利用兩張輔助圖來填補這個空白。編程
這裏補充下無縫滾動,直接看代碼,複製最後一張圖片放置第一張圖片前,同時複製第一張圖片放置最後一張圖片的後面。而且,將第一張圖片輔助圖(其實是實際顯示的第5張圖片隱藏起來,故設置style="left: -600px;")設計模式
CSS修飾數組
1、對盒子模型,文檔流的理解,絕對定位問題。
二、注意list的overflow:hidden;只顯示窗口的一張圖片,把左右兩邊的都隱藏起來。
三、確保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)
}
運行,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)
)
就算是初學者也要特別注意代碼規範問題,上面的CSS實在太不規範了,難怪我帶的人都不怎樣,哈哈哈。。。
這裏推薦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
最後,咱們完成了一個簡單的輪播圖,在個人 Github 裏能夠找到源碼。以爲不錯就star一下。