原生js圖片漸變輪播

原生js實現的圖片輪播左右滑動效果函數封裝

方便之後須要的時候拿出來複用。 適合新手學習使用。

使用方法
輪播圖的html結構就很少說了。不過有一點:爲了實現無縫無限輪播,須要在三張圖片的最前面和最後面再額外添加兩張圖片(見下),原理簡單說就是當圖片滑動到最後一張時立馬跳到第二張,眼睛看上去就像先後無縫同樣。

html

把img_slider.js引入html,而後編輯window.onload = (function () { ··· });中的內容。 (獲取圖片牀,按鈕,標識等元素。而後調用slideImg( container, btn_next, btn_prev, small_dots, img_num, auto_move_interval, move_speed ) 函數web

window.onload = (function () {
    var banner_container = document.getElementsByClassName('banners-container')[0];  //大banner圖片牀
    var next = document.getElementsByClassName('next')[0];
    var prev = document.getElementsByClassName('prev')[0];
    var buttons = document.getElementsByClassName('buttons')[0].getElementsByTagName('span');  //小圓點標識

    slideImg(banner_container, next, prev, buttons, 3, 3000, 26);  //參數說明見功能實現↓
});
//參數說明:                                      // Parameter Description:
// container:圖片牀;                             // Container: your Photos on it;
// btn_next, btn_prev:切換按鈕;                  // Btn_next, btn_prev: toggle button(next&prev);
// small_dots:小圓點標識;                        // Small_dots: small dot mark which picture now on focus;
// img_num:圖片數量(不包括先後的附圖);           // Img_num: how many pictures you have.(not including the first one and last one figures pictures);
// move_speed:圖片移動速度(數值越小越快!);        // Move_speed: image moving speed (the smaller the value, the faster!);

  


 

源碼:app

HTML&CSSide

  1 <!-- Created by zhangboyuan-XD on 2016/5/20 -->
  2 <!--
  3 注意!若是須要顯示圖片位置的小圓點標識則必須按照demo中的格式書寫!
  4 notice! If you need to display a small dot image location identification must be written in accordance with the format of the demo!
  5 -->
  6 
  7 <!doctype html>
  8 <html lang="en">
  9 <head>
 10     <meta charset="UTF-8">
 11     <title>imgSlider demo</title>
 12     <style>
 13         * {
 14             margin:0;
 15             padding:0;
 16             -webkit-box-sizing:border-box;
 17             -moz-box-sizing:border-box;
 18             box-sizing:border-box;
 19         }
 20 
 21         li {
 22             list-style:none;
 23         }
 24 
 25         .clear-float:after {
 26             content:'';
 27             width:0;
 28             height:0;
 29             display:block;
 30             clear:both;
 31         }
 32 
 33         .banners-container {
 34             position:absolute;
 35             width:5900px;
 36             height:340px;
 37             z-index:1;
 38         }
 39 
 40         .banner-wrapper {
 41             position:relative;
 42             width:1180px;
 43             height:340px;
 44             overflow:hidden;
 45             z-index:3;
 46         }
 47 
 48         .banner-wrapper img {
 49             float:left;
 50         }
 51 
 52         .banner-wrapper .btn {
 53             position:absolute;
 54             top:146px;
 55             display:block;
 56             width:24px;
 57             height:48px;
 58             -moz-opacity:.5;
 59             opacity:.5;
 60             z-index:3;
 61         }
 62 
 63         .banner-wrapper .next {
 64             right:0;
 65             background:url("image/arrow.jpg") no-repeat 0 -48px;
 66         }
 67 
 68         .banner-wrapper .prev {
 69             left:0;
 70             background:url("image/arrow.jpg") no-repeat;
 71         }
 72 
 73         .banner-wrapper .buttons {
 74             position:absolute;
 75             height:16px;
 76             width:100px;
 77             bottom:10px;
 78             left:590px;
 79             z-index:3;
 80         }
 81 
 82         .banner-wrapper .buttons span {
 83             float:left;
 84             border:1px solid #fff;
 85             width:16px;
 86             height:16px;
 87             margin-right:15px;
 88             border-radius:50%;
 89             -webkit-border-radius:50%;
 90             -moz-border-radius:50%;
 91             background:#fff;
 92             cursor:pointer;
 93         }
 94 
 95         .banner-wrapper .buttons .on {
 96             border-color:#5c5c5c;
 97             background:#5c5c5c;
 98         }
 99     </style>
100 </head>
101 <body>
102 <div class="banner-wrapper">
103     <ul class="banners-container clear-float" style="left:-1180px;">
104         <!-- 這裏先後多出來的兩張圖是爲了實現無限循環 Before and after the extra two <li> is to achieve an infinite loop -->
105         <li><a href="#"><img src="image/banner_3.jpg" alt="banner"></a></li>
106         <li><a href="#"><img src="image/banner_1.gif" alt="banner"></a></li>
107         <li><a href="#"><img src="image/banner_2.jpg" alt="banner"></a></li>
108         <li><a href="#"><img src="image/banner_3.jpg" alt="banner"></a></li>
109         <li><a href="#"><img src="image/banner_1.gif" alt="banner"></a></li>
110     </ul>
111     <a class="next btn" href="#"></a>
112     <a class="prev btn" href="#"></a>
113     <div class="buttons">
114         <!--注意:顯示輪播圖進度的小圓點,必須給span設置對應的index屬性1,2,3,··· -->
115         <span index="1" class="on"></span>
116         <span index="2"></span>
117         <span index="3"></span>
118     </div>
119 </div>
120 <script src="img_slider.js"></script>
121 </body>
122 </html>

 

JavaScript函數

  1 /*
  2  *   Created by zhangboyuan-XD on 2016/5/20.
  3  *
  4  *   注意!若是須要顯示圖片位置的小圓點標識則必須按照demo中的格式書寫!
  5  *   notice! If you need to display a small dot image location identification must be written in accordance with the format of the demo!
  6  */
  7 
  8 window.onload = (function () {
  9     var banner_container = document.getElementsByClassName('banners-container')[0];  //大banner圖片牀
 10     var next = document.getElementsByClassName('next')[0];
 11     var prev = document.getElementsByClassName('prev')[0];
 12     var buttons = document.getElementsByClassName('buttons')[0].getElementsByTagName('span');  //小圓點標識
 13 
 14     slideImg(banner_container, next, prev, buttons, 3, 3000, 26);  //參數說明見功能實現↓
 15 });
 16 
 17 
 18 
 19 
 20 /**功能實現********************功能實現***********************功能實現********************功能實現*********************功能實現****************************************************/
 21 
 22 //參數說明:                                      // Parameter Description:
 23 // container:圖片牀;                             // Container: your Photos on it;
 24 // btn_next, btn_prev:切換按鈕;                  // Btn_next, btn_prev: toggle button(next&prev);
 25 // small_dots:小圓點標識;                        // Small_dots: small dot mark which picture now on focus;
 26 // img_num:圖片數量(不包括先後的附圖);           // Img_num: how many pictures you have.(not including the first one and last one figures pictures);
 27 // move_speed:圖片移動速度(數值越小越快!);        // Move_speed: image moving speed (the smaller the value, the faster!);
 28 function slideImg(container, btn_next, btn_prev, small_dots, img_num, auto_move_interval, move_speed) {
 29     var index = 1; //當前圖片下小圓點標識  //current picture identification dot
 30     var img_width = -parseInt(container.style.left); //每張圖片寬
 31     var timer = null;
 32     var animated = false; //判斷是否移動完成  //To determine whether the move is complete
 33     var active_buttons = false;
 34     var active_btn_next = false;
 35     var active_btn_prev = false;
 36     var active_auto_move = false;
 37 
 38     if (typeof(container) != 'object') {
 39         alert("圖片牀參數傳入錯誤!");
 40         return;
 41     }
 42     if (typeof(btn_next) == 'object') active_btn_next = true;
 43     if (typeof(btn_prev) == 'object') active_btn_prev = true;
 44     if (typeof (small_dots) == 'object') active_buttons = true;
 45     if (typeof(img_num) != 'number') {
 46         alert("parameter \"img_num\" is not right!");
 47         return;
 48     }
 49     if (typeof(auto_move_interval) == 'number') active_auto_move = true;
 50     if (typeof(move_speed) != 'number') {
 51         move_speed = 20;
 52         alert("ERROR:Function \"slideImg()\", parameter \"move_speed\" is not right!已自動修正爲20!快謝謝我爲你挽救了一切,走上人生巔峯,贏取白富美。哈哈哈哈! -zby")
 53     }
 54 
 55     //移動圖片牀
 56     function animate(offset) {
 57         if (offset == 0) {
 58             return;
 59         }
 60         animated = true;
 61         var auto_move_interval = 10;  //每次移動間隔時間
 62         var new_left = parseInt(container.style.left) + offset;  //目標圖片對應的left值  //Target image corresponding to the left value
 63 
 64         //平滑移動函數
 65         var move = function () {
 66             var cur_left = parseInt(container.style.left);    //當前left值
 67             var move_spacing = (new_left - cur_left) / move_speed;     //移動間隔(逐漸減少,實現平滑移動)//Movement interval (gradually reduced, to achieve a smooth movement)
 68             move_spacing = move_spacing > 0 ? Math.ceil(move_spacing) : Math.floor(move_spacing); //速度取整
 69             //當速度大於0且當前left值小於目標left值時,向右移動圖片牀        // 當速度小於0且當前left值大於目標left值時,向左移動圖片牀
 70             if ((move_spacing > 0 && parseInt(container.style.left) < new_left) || (move_spacing < 0 && parseInt(container.style.left) > new_left)) {
 71                 container.style.left = parseInt(container.style.left) + move_spacing + 'px';
 72                 setTimeout(move, auto_move_interval);
 73             }
 74             else {
 75                 //移動完成
 76                 container.style.left = new_left + 'px';
 77                 if (new_left > -img_width) {
 78                     container.style.left = -img_width * img_num + 'px';
 79                 }
 80                 if (new_left < -img_width * img_num) {
 81                     container.style.left = -1180 + 'px';
 82                 }
 83                 animated = false;
 84             }
 85         };
 86         //入口  //Entrance
 87         move();
 88     }
 89 
 90 
 91     //右點擊,左點擊
 92     btn_next.onclick = (function () {
 93         if (!active_btn_next) return;
 94 
 95         //判斷,若是移動未完成則不進行下一次移動。
 96         if (animated) {
 97             return;
 98         }
 99         animate(-img_width);
100         //小圓點標識更新  //update small dot
101         if (index == img_num) index = 1;
102         else  index += 1;
103         showButton();
104     });
105     btn_prev.onclick = (function () {
106         if (!active_btn_prev) return;
107 
108         if (animated) {
109             return;
110         }
111         animate(img_width);
112         if (index == 1) index = img_num;
113         else  index -= 1;
114         index -= 1;
115         showButton();
116     });
117 
118 
119     //點亮,熄滅小圓點
120     function showButton() {
121         if (!active_buttons) return;
122 
123         //熄滅過去圓點
124         for (var i = 0; i < small_dots.length; i++) {
125             if (small_dots[i].className == 'on') {
126                 small_dots[i].className = '';
127                 break;
128             }
129         }
130         //點亮當前小圓點
131         small_dots[index - 1].className = 'on';
132     }
133 
134     //點擊小圓點切換圖片   //Click the dots to change images
135     for (var i = 0; i < small_dots.length; i++) {
136         if (!active_buttons) return;
137 
138         small_dots[i].onclick = (function () {
139             if (this.className == 'on' || animated) return;
140             var targetIndex = parseInt(this.getAttribute('index'));
141             var offset = -img_width * (targetIndex - index);
142             index = targetIndex;
143             animate(offset);
144             showButton();
145         });
146     }
147 
148 
149     //自動輪播  //auto play
150     function play() {
151         if (!active_auto_move) return;
152 
153         timer = setTimeout(function () {
154             if (animated) {
155                 return;
156             }
157             animate(-img_width);
158             if (index == img_num) index = 1;
159             else  index += 1;
160             showButton();
161             play();
162         }, auto_move_interval);
163     }
164 
165     function stop() {
166         clearTimeout(timer);
167     }
168 
169     //鼠標移入暫停輪播
170     container.onmouseover = stop;
171     container.onmouseout = play;
172     //自動輪播入口 //auto play entrance
173     play();
174 }
相關文章
相關標籤/搜索