手把手原生js簡單輪播圖

     在團隊帶人,忽然被人問到輪播圖如何實現,進入前端領域有一年多了,但好久沒本身寫過,一直是用大牛寫的插件,今天就寫個簡單的適合入門者學習的小教程。固然,輪播圖的實現原理與設計模式有不少種,我這裏講的是用面向過程函數式編程去實現,相對於面向對象設計模式,代碼不免會顯得臃腫冗餘。但沒有面向對象的抽象卻很適合新手理解與學習。已經在BAT的同窗看到但願少噴點。另外能夠多提意見。javascript

 

輪播圖的原理:css

一系列的大小相等的圖片平鋪,利用CSS佈局只顯示一張圖片,其他隱藏。經過計算偏移量利用定時器實現自動播放,或經過手動點擊事件切換圖片。html

 

Html佈局前端

    首先父容器container存放全部內容,子容器list存在圖片。子容器buttons存放按鈕小圓點。java

 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">&lt;</a>
19         <a href="javascript:;" id="next" class="arrow">&gt;</a>
20     </div>

 

優化,無縫滾動。git

當你從最後一張圖切換回第一張圖時,有很大空白,利用兩張輔助圖來填補這個空白。github

這裏補充下無縫滾動,直接看代碼,複製最後一張圖片放置第一張圖片前,同時複製第一張圖片放置最後一張圖片的後面。而且,將第一張圖片輔助圖(其實是實際顯示的第5張圖片隱藏起來,故設置style="left: -600px;"編程

 

CSS修飾設計模式

1、對盒子模型,文檔流的理解,絕對定位問題。數組

二、注意listoverflow: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)
}
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">&lt;</a>
208         <a href="javascript:;" id="next" class="arrow">&gt;</a>
209     </div>
210 
211 </body>
212 
213 </html>
點擊有驚喜

 

這裏結合評論,補充下:

就算是初學者也要特別注意代碼規範問題,上面的CSS實在太不規範了,難怪我帶的人都不怎樣,哈哈哈。。。

  1. Css的書寫順序
  2. CSS裏最好不用或直接不用id來改變樣式(我這裏是id爲了方便DOM操做)

這裏推薦css規範的技術文章

前端前輩的博客:  http://www.cnblogs.com/hustskyking/p/css-spec.html

或者這位大神的Githubhttps://github.com/fex-team/styleguide/blob/master/css.md

以及KISSY v1.4 Documentationcss編碼規範: http://docs.kissyui.com/1.4/docs/html/tutorials/style-guide/css-coding-style.html

over

最後,咱們完成了一個簡單的輪播圖,在個人  Github  裏能夠找到源碼。以爲不錯就star一下。

相關文章
相關標籤/搜索