JS實(shí)現(xiàn)圖片輪播效果

源代碼已上傳 Github: https://github.com/axiang12/SliderAnimate
在網(wǎng)頁瀏覽中,可以看到輪播圖是無處不在的,這是一個(gè)前端攻城獅最基本的技巧。首先看看幾個(gè)網(wǎng)頁的呈現(xiàn)圖片輪播的效果。
QQ音樂:
qq音樂.png
網(wǎng)易云音樂:
網(wǎng)易云音樂.png
天 貓:
天貓.png

接下來將從簡到難總結(jié)幾種JS實(shí)現(xiàn)圖片輪播的方法。

1、樣式一:鼠標(biāo)滑入滑出實(shí)現(xiàn)圖片切換
當(dāng)鼠標(biāo)滑入到小圓點(diǎn)上時(shí),顯示當(dāng)前對應(yīng)的圖片,鼠標(biāo)移出時(shí)回到默認(rèn)的圖片。如果點(diǎn)擊了小圓點(diǎn),顯示當(dāng)前的圖片,移出時(shí)仍不改變顯示。
html+css設(shè)置
 1 <!-- 輪播圖片 -->
 2 <div class="slider">
 3     <!-- 小圓點(diǎn) -->
 4     <div class="control">
 5         <!-- 根據(jù)圖片數(shù)量添加小圓點(diǎn) -->
 6         <ul>
 7             
 8         </ul>
 9     </div>
10     <!-- 圖片顯示 -->
11     <div class="content">
12         ![](./22.jpg)
13         ![](./66.jpg)
14         ![](./33.jpg)
15         ![](./44.jpg)
16         ![](./55.jpg)
17     </div>
18 </div>
1 /*css樣式*/
 2 *{margin: 0;padding: 0;}
 3 
 4 .slider{
 5     margin: 100px auto;
 6     width: 640px;
 7     height: 400px;
 8     position: relative;
 9 }
10 .slider .control{
11     position: absolute;
12     width: 640px;
13     height: 20px;
14     left: 0;
15     bottom: 30px;
16 }.slider .control ul{
17     list-style: none;
18     width: 150px;
19     margin: 0 auto;
20 }.slider .control li{
21     width: 20px;
22     height: 20px;
23     margin: 0 5px;
24     float: left;
25     border-radius: 50%;
26     background-color: #fff;
27     cursor: pointer;
28 }
29 .slider .control li.active{
30     background-color: red;
31 }/*默認(rèn)設(shè)置不顯示其他圖片*/
32 .slider .content img{
33     width: 640px;
34     height: 400px;
35     display: none;
36 }
37 /*只顯示第一張圖片*/
38 .slider .content img.active{
39     display: block;
40 }
樣式展示效果:
1樣式.png
javascript設(shè)置
 1 //定義一個(gè)改變圖片函數(shù)
 2 function changImage(i) {
 3     var index = i;
 4     var ul = document.getElementsByTagName("ul")[0];
 5     //獲取所有的images
 6     var images = document.getElementsByTagName("img"); //數(shù)組
 7     //獲取所有的li
 8     var lis = ul.getElementsByTagName("li");
 9     for(var j = 0; j < lis.length; j++){
10         var li = lis[j];
11          var img = images[j];
12          //清除li 和 img 默認(rèn)的active (img的active表示顯示這個(gè)圖片)
13          li.className = '';
14          img.className = '';
15     }
16     //設(shè)置當(dāng)前的active屬性
17     
18     lis[index].className = 'active';
19     images[index].className = 'active';
20 }
21         
22 window.onload = function () {
23     //根據(jù)圖片數(shù)改變小圓點(diǎn)數(shù)
24     //1獲得圖片數(shù)
25     var content = document.getElementsByClassName("content")[0];
26     var images = content.getElementsByTagName("img"); //數(shù)組  所有圖片
27     //圖片數(shù)
28     var imageCount = images.length;
29     //根據(jù)圖片數(shù)創(chuàng)建小圓點(diǎn)數(shù),添加到ul中
30     //遍歷圖片數(shù)
31     for(var i = 0; i < imageCount; i++){
32         //1創(chuàng)建小白點(diǎn)
33         var li = document.createElement("li")
34         li.index = i;
35         //3默認(rèn)的第一個(gè)選中
36         if (i == 0) {
37             li.className += 'active';
38         }
39         //2添加到ul中
40         var control = document.getElementsByClassName("control")[0];
41         var ul = control.getElementsByTagName("ul")[0];
42         ul.appendChild(li)
43         var select = 0;
44         li.onclick = function(){
45             select = this.index;
46             changImage(this.index);
47         
48         li.onmousemove = function () {
49             changImage(this.index);
50         
51         li.onmouseout =function () {
52             changImage(select);
53         
54     
55         //4設(shè)置ul寬度 保證居中
56         ul.style.width = (imageCount*30)+ 'px';    
57     }
2、樣式二:實(shí)現(xiàn)圖片自動切換
展示時(shí),圖片在頁面中自動切換。鼠標(biāo)點(diǎn)擊小圓點(diǎn),直接切換顯示當(dāng)前圖片。
html+css設(shè)置(基本和上面一樣)
 1 <body>
 2 <div class="slider">
 3     <div class="control">
 4         <span class="current">1</span>
 5         <span>2</span>
 6         <span>3</span>
 7         <span>4</span>
 8         <span>5</span>
 9     </div>
10     <div class="content" id="imag-list">
11         <ul >
12             <li>![](images/1.jpg)</li>
13             <li>![](images/5.jpg)</li>
14             <li>![](images/4.jpg)</li>
15             <li>![](images/3.jpg)</li>
16             <li>![](images/2.jpg)</li>
17         </ul>
18     </div>
19 </div>
20 </body>
*{padding: 0;margin: 0;}
.slider{
    width: 800px;
    height: 500px;
    position: relative;
    overflow: hidden;
    margin: 30px auto;
}
.slider img{
    width: 800px;
    height: 500px;
}

.slider .content{
}
.slider .content ul{
    width: 10000px;
    list-style: none;
    position: absolute;
    left:0px;
}
.slider .content li{
    float: left;

.slider .control{
    position: absolute;
    width: 100%;    
    z-index: 10;
    bottom: 50px;
    left: 0;
    text-align: center;
}
.slider .control span{
    display: inline-block;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 14px;
    background-color: #fff;
    border-radius: 50%;
    cursor: pointer;
}
.slider .control span.current{
    background-color: red;
}
JavaScript設(shè)置
 1 //封裝移動函數(shù)
 2     function animate(element,target){
 3         clearInterval(element.animateTimer);
 4         var left = element.offsetLeft;
 5         var step = (target - left) / 10;
 6         element.animateTimer = setInterval(function(){
 7             left += step;
 8             element.style.left = left + 'px';
 9             if(Math.abs(target - left) <= Math.abs(step)){
10                 clearInterval(element.animateTimer);
11                 element.style.left = target + 'px';
12             }
13         },100);
14     }

15     window.onload =function(){
16         var ul = document.getElementsByTagName('ul')[0];
17         var spanArr = document.getElementsByTagName('span');
18         //4.最后一張顯示后,克隆第一張圖片繼續(xù)顯示第一張
19         ul.appendChild(ul.children[0].cloneNode(true));
20         var ulLeft = ul.offsetLeft;
21         console.log(ulLeft);
22         var ulIndex = 0;  //默認(rèn)第一張圖片下標(biāo)
23         // console.log(ulLeft);
24         //開啟
25         var autoPlayTimer = setInterval(function(){            
26             //4.2 從最后一張滾回到第一張(ulIndex == 5)之后  需重置回第一張狀態(tài)
27             if(ulIndex == 5){
28                 ulIndex = 0;
29                 ul.style.left = '0';
30                 ulLeft = 0;
31             }
32             ulLeft -= 800;
33             // console.log(ulLeft);
34             animate(ul, ulLeft);
35             ulIndex++;
36             for(var i = 0; i< spanArr.length; i++){
37                 spanArr[i].className = '';
38             }
39             //4.3改變頁面  第五張圖片結(jié)束后ulIndex是4 
40             //第六張圖片即第一張圖片的ulIndex是5  所以求ulIndex % 5恢復(fù)ulIndex為0 
41             spanArr[ulIndex % 5].className = 'current';
42         },3000);
43         //第二大步  給小圓點(diǎn)span添加點(diǎn)擊事件
44         for(var i = 0; i< spanArr.length; i++){
45             var span = spanArr[i];
46             span.index = i;
47             span.onclick = function(){
48                 //實(shí)現(xiàn)點(diǎn)擊span后圖片移動
49                 var targetLeft = -800 * this.index; //0 - 4
50                 //點(diǎn)擊后自動滾動到 當(dāng)前圓點(diǎn)對應(yīng)的圖片的位置  即左移800*下標(biāo)
51                 animate(ul, targetLeft);
52                 //記錄此時(shí)的ulLeft ulIndex 為了繼續(xù)從當(dāng)前點(diǎn)擊圖片向下一張圖片移動
53                 ulLeft = targetLeft;
54                 ulIndex = this.index;
55                 //切換當(dāng)前span選中樣式
56                 for(var j = 0; j<spanArr.length; j++){
57                     spanArr[j].className = '';
58                 }
59                 this.className = 'current';
60             }
61         }
62     }
3、樣式三:實(shí)現(xiàn)帶有箭頭的輪播圖
展示時(shí),圖片在頁面中自動切換,橫條隨之選中。點(diǎn)擊左箭頭,圖片向左滑動;點(diǎn)擊右箭頭,圖片向右滑動。 鼠標(biāo)點(diǎn)擊小圓點(diǎn),直接切換顯示當(dāng)前圖片。鼠標(biāo)放入圖片中,停止圖片滑動,移開時(shí)繼續(xù)滑動。
html+css設(shè)置
1 <body>
 2     <div class="box">
 3         <div class="content">
 4             <div>![](img/1.jpg)</div>
 5             <div>![](img/2.jpg)</div>
 6             <div>![](img/3.jpg)</div>
 7             <div>![](img/4.jpg)</div>
 8             <div>![](img/5.jpg)</div>
 9             <div>![](img/6.jpg)</div>
10             <div>![](img/7.jpg)</div>
11         </div>
12         <div class="control">
13             <!-- <span class="control-bar current"></span> -->
14             <!-- <span class="control-bar"></span>
15             <span class="control-bar"></span>
16             <span class="control-bar"></span>
17             <span class="control-bar"></span>
18             <span class="control-bar"></span>
19             <span class="control-bar"></span> -->
20         </div>
21 
22         <span id="pre"></span>
23         <span id="next"></span>
24     </div>
25 </body>
1 *{margin: 0;padding: 0;}
 2 
 3 .box{
 4     width: 310px;
 5     height: 250px;
 6     margin: 100px auto;
 7     overflow: hidden;
 8     position: relative;
 9 }
10 .content{
11     width: 310px;
12     height: 220px;
13     overflow: hidden;
14     position: relative;
15 }
16 .content div{
17     position: absolute;
18     top: 0;
19     left: 0;
20 }
21 .content div img{
22     width: 310px;
23     height: 220px;
24 }
25 
26 
27 .control{
28     width: 310px;
29     height: 30px;
30     background-color: #333;
31     text-align: center;
32 }
33 .control-bar{
34     display: inline-block;
35     width: 24px;
36     height: 5px;
37     background: url(img/icon.png) no-repeat -24px -790px ;
38     margin: 12px 2px 0 2px;
39     cursor: pointer;
40 }
41 .control .control-bar:hover{
42     background: url('img/icon.png') no-repeat -24px -770px;
43 }
44 
45 .control .control-bar.current{
46     background: url('img/icon.png') no-repeat 0 -770px;
47 }
48 #pre, #next{
49     position: absolute;
50     top: 50%;
51     margin-top: -35px;
52     width: 20px;
53     height: 34px;
54     background-color: pink;
55     cursor: pointer;
56 }    
57 #pre{
58     left: 3px;
59     background:url(img/icon.png) no-repeat 0 0;
60 }
61 #next{
62     right: 3px;
63     background:url(img/icon.png) no-repeat -9px -45px;
64 }
樣式效果如圖:
樣式3.png
javascript設(shè)置
思路:box設(shè)置overflow:hidden屬性,第一張圖片顯示在box中,其余圖片均隱藏放置在第一張圖的右邊。當(dāng)開啟動畫時(shí),第一張圖片向左移動隱藏,下一張圖片向左移動顯示,依次類推,當(dāng)顯示完最后一張時(shí),繼續(xù)回到顯示第一張圖片,圖片輪播效果就實(shí)現(xiàn)了。
 1 // 前面內(nèi)容已講過
  2 // 封裝好的獲取屬性函數(shù)
  3 function getStyle(element, styleName){
  4     if(element.currentStyle){
  5         return element.currentStyle[styleName];
  6     }else{
  7         var computedStyle = window.getComputedStyle(element, null);
  8         return computedStyle[styleName];
  9     }
 10 }
 11 //封裝好的動畫函數(shù)
 12 function animate(element,json){
 13     clearInterval(element.timer);
 14     var isStop = false;
 15     element.timer = setInterval(function(){
 16         isStop = true;
 17         for(var key in json){
 18             var current = parseInt(getStyle(element, key));
 19             var target = json[key];
 20             var step = (target - current) / 10;
 21             step = step > 0 ? Math.ceil(step) : Math.floor(step);
 22             current += step;
 23             if(Math.abs(target -current) > Math.abs(step)){
 24                 isStop = false;
 25             }else{ 
 26                 current = target;
 27             }
 28             element.style[key] = current + 'px';    
 29         }
 30         if(isStop){
 31             clearInterval(element.timer);
 32         }
 33     },30);
 34 }
 35 
 36 //實(shí)現(xiàn)輪播圖
 37 window.onload = function(){
 38     var box = document.getElementsByClassName('box')[0];
 39     var contentBox = document.getElementsByClassName('content')[0];
 40     var controlBox = document.getElementsByClassName('control')[0];
 41     var imageDivArr = contentBox.getElementsByTagName('div');
 42 
 43     var currentIndex = 0;
 44     var boxWidth = box.offsetWidth;
 45     //1.動態(tài)創(chuàng)建橫條
 46     for(var i= 0; i < imageDivArr.length; i++){
 47         var span = document.createElement('span');
 48         if(i == 0){
 49             span.className = 'control-bar current';
 50         }else{
 51             span.className = 'control-bar'; 
 52         }
 53         span.index = i;
 54         controlBox.appendChild(span);
 55 
 56         //6.設(shè)置span點(diǎn)擊事件
 57         span.onclick = function(){
 58             //如果當(dāng)前點(diǎn)擊的按鈕,就是當(dāng)前的按鈕則不作操作
 59             if(currentIndex != this.index){
 60 
 61                 //點(diǎn)擊的圖片,在當(dāng)前圖片的右邊
 62                 if(this.index > currentIndex){
 63                     //當(dāng)前的圖片向左移  移除當(dāng)前位置
 64                     animate(imageDivArr[currentIndex],{left:-boxWidth});
 65 
 66                     //此時(shí)被點(diǎn)擊對應(yīng)的圖片放在顯示框右邊 再進(jìn)行向左移
 67                     currentIndex = this.index;
 68                     imageDivArr[currentIndex].style.left = boxWidth;
 69 
 70                 }else{ //點(diǎn)擊的圖片,在當(dāng)前圖片的右邊
 71                     animate(imageDivArr[currentIndex],{left:boxWidth});
 72 
 73                     currentIndex = this.index;
 74                     imageDivArr[currentIndex].style.left = boxWidth;
 75                 }
 76 
 77                 //
 78                 animate(imageDivArr[currentIndex], {left : 0})
 79                 //刷新控制條
 80                 refresh();
 81             }
 82         }
 83     }
 84 
 85     //2.放置圖片位置
 86     // var boxWidth = box.offsetWidth;
 87     for(var i= 0; i < imageDivArr.length; i++){
 88         var imgDiv = imageDivArr[i];
 89         imgDiv.style.left = boxWidth + 'px';
 90     }
 91     imageDivArr[0].style.left = '0';
 92 
 93 
 94     //3.從左邊劃入
 95     // var currentIndex = 0;
 96     function nextImage(){
 97         animate(imageDivArr[currentIndex],{left:-boxWidth});
 98     
 99         currentIndex++;
100     
101         if(currentIndex >= imageDivArr.length){
102             currentIndex = 0;
103         }
104         imageDivArr[currentIndex].style.left = boxWidth + 'px';
105     
106         animate(imageDivArr[currentIndex],{left:0});
107         refresh();
108     }
109 
110     //3.1從右邊劃入
111     function prevImage(){
112         animate(imageDivArr[currentIndex],{left:boxWidth}); //最后一張currentIndex = 6
113     
114         currentIndex--;
115     
116         if(currentIndex < 0){
117             currentIndex = imageDivArr.length - 1;  //返回到最后一張
118         }
119         imageDivArr[currentIndex].style.left = (-boxWidth) + 'px';
120     
121         animate(imageDivArr[currentIndex],{left:0});
122         refresh();
123     }
124 
125     //4.刷新橫條顯示
126     function refresh(){
127         for(var i = 0; i < controlBox.children.length; i++ ){
128             // console.log(controlBox.children[i]);
129             var bar = controlBox.children[i];
130             bar.className = 'control-bar'
131             // console.log(bar);
132         }
133         controlBox.children[currentIndex].className = 'control-bar current';
134     }
135 
136     //點(diǎn)擊箭頭切換
137     document.getElementById('next').onclick = nextImage;
138     document.getElementById('pre').onclick = prevImage;
139 
140     //自動播放
141     var timer = setInterval(nextImage,2000);
142 
143     box.onmouseover = function (){
144         clearInterval(timer);
145     }
146     //移出時(shí),重新開始定時(shí)器
147     box.onmouseout = function (){
148         timer = setInterval(nextImage ,2000);    
149     }
150 }
4、“旋轉(zhuǎn)木馬”輪播圖
旋轉(zhuǎn)木馬樣式圖.png
html+css樣式設(shè)置
<body>
    <div class="box">
        
        <!-- 圖片設(shè)置 -->
        <div class="content">
            <ul>
                <li>![](images/slidepic1.jpg)</li>
                <li>![](images/slidepic2.jpg)</li>
                <li>![](images/slidepic3.jpg)</li>
                <li>![](images/slidepic4.jpg)</li>
                <li>![](images/slidepic5.jpg)</li>
            </ul>
        </div>
        
        <!-- 左右箭頭設(shè)置 -->
        <div class="control">
            <a href="javascript:;" id="prev"></a>
            <a href="javascript:;" id="next"></a>
        </div>
    </div>
</body>
*{margin: 0;padding: 0;}
ul{list-style: none;}
/*大盒子*/
.box{
    width: 1000px;
    margin: 5px auto;
    position: relative;
    background-color: pink;
}

/*左右箭頭*/
#next, #prev{
    position: absolute;
    width: 76px;
    height: 112px;
    top: 0;
    background: url(../images/next_1.png) no-repeat 0 0;
    z-index: 5;
}
#next{
    right: 10px;
}
#prev{
    left: 10px;
    background: url(../images/prev_1.png) no-repeat 0 0;
}


.box .content li{
    position: absolute;

}
.box .content li img{
    width: 100%;
}

/*可以通過css設(shè)置定位
.box .content li.li1{
    width: 300px;
    opacity: 0.4;
    top: 30px;
    left: 50px;
    z-index: 1;
}
.box .content li.li2{
    width: 400px;
    opacity: 0.7;
    top: 100px;
    left: 0;
    z-index: 2;
}
.box .content .li3{
    width: 600px;
    opacity: 1;
    top: 200px;
    left: 200px;
    z-index: 3;
}
.box .content .li4{
    width: 400px;
    opacity: 0.7;
    right: 0;
    top: 100px;
    z-index: 2;
}
.box .content .li5{
    width: 300px;
    opacity: 0.4;
    top: 30px;
    right: 50px;
    z-index: 1;
}
*/
javascript設(shè)置
    window.onload =function () {
        //定位置 五個(gè)位置對應(yīng)五個(gè)json對象,放入數(shù)組中,可以靈活的獲取這些json對象
        var json = [{
            width: 300,
            opacity: 0.4,
            top: 30,
            left: 50,
            zIndex: 1
        },{
            width: 400,
            opacity: 0.7,
            top: 100,
            left: 20,
            zIndex: 2
        },{
            width: 700,
            opacity: 1,
            top: 200,
            left: 150,
            zIndex: 3
        },{
            width: 400,
            opacity: 0.7,
            top: 100,
            left: 580,
            zIndex: 2
        },{
            width: 300,
            opacity: 0.4,
            top: 30,
            left: 650,
            zIndex: 1
        }];

        refreshImageLocation(0);
        function refreshImageLocation(index){
            //默認(rèn)情況下 第i個(gè)對應(yīng)i-index個(gè)位置
            var liArr = $('li');
            console.log(liArr);
            for(var i = 0; i < liArr.length; i++){
                var li = liArr[i];
                var locationIndex = i - index;

                if(locationIndex < 0){
                    locationIndex += 5;
                }

                var locationDate = json[locationIndex];
                console.log(locationDate);

                animate(li, locationDate, null);
            }
        }

        var index = 0;
        //設(shè)置點(diǎn)擊箭頭事件
        $('#next').onclick = function(){
            // console.log('#next');
            index++;
            if(index == 5){
                index = 0;
            }
            refreshImageLocation(index);
        }

        $('#prev').onclick = function(){
            index--;
            if(index < 0){
                index = 4;
            }
            refreshImageLocation(index);
        }
        
    }

以上就是較為常用的 JS實(shí)現(xiàn)輪播圖片效果的方法,如果有更好的方法可以討論交流。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,109評論 25 709
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,408評論 4 61
  • 黑白國是一個(gè)很可憐的國家。那里一切都是黑白的。黑白的人、黑白的汽車、黑白的房屋······連彩虹都是黑白的。...
    Amyanne閱讀 473評論 0 0
  • 姜濤東北腔好濃,好做 羅蘭,謝霆鋒港味風(fēng) 韓國小生,白冰話題女王 謝的爹的是黃秋聲,頭文字d感 竟然還有葛大爺,葛...
    極佳hv閱讀 372評論 0 0
  • Q:和寶寶一起讀書時(shí),我試圖按照專家的建議,開發(fā)孩子的想象力。但是每次我提出建議,讓他來猜猜接下來會發(fā)生什么,他總...
    老約翰夢多多館Jeny分享閱讀 176評論 0 0

友情鏈接更多精彩內(nèi)容