JavaScript五种方式实现图片轮播

实现图片轮播的主要思路总结:

  1、将多张图片水平或者垂直方向衔接排好,沿着某一个方式移动,父元素设置固定的大小,溢出的内容进行隐藏

  2,通过position条件下:z-index的覆盖显示。

  3、改变透明度实现图片轮播

 

基于上面的思路,下面是五种实现的方式:

 

方式一:vue + swiper 实现图片轮播

1、安装swiper

     npm install swiper

2、在组件中引用swiper

    import Swiper from 'swiper';

    import 'swiper/dist/css/swiper.min.css';

3、实例代码:

  1 <template>
  2   <div class="slide" v-on:mouseover="stop()" v-on:mouseout="move()">
  3     <div class="slideshow">
  4       <transition-group tag="ul" name="image">
  5         <li v-for="(img, index) in imgArray" v-show="index===mark" :key="index">
  6           <a href="#">
  7             <img :src='img'>
  8           </a>
  9         </li>
 10       </transition-group>
 11     </div>
 12     <div class="bar">
 13       <span v-for="(item, index) in imgArray" :class="{ 'active':index===mark }"
 14       @click="change(index)" :key="index"></span>
 15     </div>
 16   </div>
 17 </template>
 18 
 19 <script>
 20 export default {
 21   data () {
 22     return {
 23       timer: null, //定时器
 24       mark: 0, //比对图片索引的变量
 25       imgArray: [//图片路径
 26         require('../../images/1.png'),
 27         require('../../images/2.png'),
 28         require('../../images/3.png'),
 29         require('../../images/4.png')  
 30       ]
 31     }
 32   },
 33   methods: {
 34     autoPlay () {
 35       this.mark++;
 36       if (this.mark === 4) {
 37         this.mark = 0
 38       }
 39     },
 40     play () {
 41       this.timer = setInterval(this.autoPlay, 2500)
 42     },
 43     change (i) {
 44       this.mark = i
 45     },
 46     stop () {
 47       clearInterval(this.timer)
 48     },
 49     move () {
 50       this.timer = setInterval(this.autoPlay, 2500)
 51     }
 52   },
 53   created () {
 54     this.play()
 55   }
 56 }
 57 </script>
 58 
 59 
 60 <style scoped>
 61   * {
 62     margin: 0;
 63     padding: 0;
 64     list-style: none;
 65   }
 66   .slide {
 67     width: 100%;
 68     height: 320px;
 69     margin: 0 auto;
 70     overflow: hidden;
 71     position: relative;
 72   }
 73   .slideshow {
 74     width: 100%;
 75     height: 320px;
 76   }
 77   .slideshow ul{
 78     width:100%;
 79     height: 320px;
 80   }
 81   li {
 82     width:100%;
 83     position: absolute;
 84   }
 85   .slideshow ul a{
 86     display: inline-block;
 87     width:100%;
 88   }
 89   img {
 90     width: 100%;
 91     height: 320px;
 92   }
 93   .bar {
 94     position: absolute;
 95     width: 100%;
 96     bottom: 10px;
 97     margin: 0 auto;
 98     z-index: 10;
 99     text-align: center;
100   }
101   .bar span {
102     width: 10px;
103     height: 10px;
104     border-radius:50%;
105     background: white;
106     display: inline-block;
107     margin-right: 10px;
108   }
109   .active {
110     background: red !important;
111   }
112   .image-enter-active {
113     transform: translateX(0);
114     transition: all 1.5s ease;
115   }
116   .image-leave-active {
117     transform: translateX(-100%);
118     transition: all 1.5s ease;
119   }
120   .image-enter {
121     transform: translateX(100%);
122   }
123   .image-leave {
124     transform: translateX(0);
125   }
126 
127 </style>

 

方式二:jQuery实现轮播图

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Document</title>
  6     <style type="text/css">
  7         .pic{
  8             width: 790px;
  9             height: 340px;
 10             margin: 10px auto;
 11             position: relative;
 12             overflow: hidden;
 13         }
 14         .content{
 15             width: 99999px;
 16             height: 340px;
 17             position: absolute;
 18             left: 0px;
 19             top: 0px;
 20 
 21         }
 22         .content img{
 23             float: left;
 24         }
 25         .index{
 26             position: absolute;
 27             left: 300px;
 28             bottom: 5px;
 29             width: 200px;
 30             height: 20px;
 31             list-style: none;
 32         }
 33         .index li{
 34             width: 10px;
 35             height: 10px;
 36             border-radius: 50%;
 37             float: left;
 38             margin-left: 10px;
 39             background-color: rgba(100,100,100,0.3);
 40         }
 41 
 42         .left{
 43             width: 30px;
 44             height:50px;
 45             background-color:rgba(100,100,100,0.5);  
 46             position: absolute;
 47             left: 0px;
 48             top: 150px;
 49             line-height: 50px;
 50             text-align: center;
 51             font-size: 20px;
 52             color: #fff;
 53             display: none;
 54         }
 55         .right{
 56             width: 30px;
 57             height:50px;
 58             background-color:rgba(100,100,100,0.5);  
 59             position: absolute;
 60             right: 0px;
 61             top: 150px;
 62             line-height: 50px;
 63             text-align: center;
 64             font-size: 20px;
 65             color: #fff;
 66             display: none;
 67         }
 68         .index .first{
 69             background-color: red;
 70         }
 71 
 72     </style>
 73     <script type="text/javascript" src="jquery/jquery-3.0.0.min.js"></script>
 74 </head>
 75 <body>
 76     <div class="pic">
 77         <div class="content">
 78             ![](images/(1).jpg)
 79             ![](images/(2).jpg)
 80             ![](images/(3).jpg)
 81             ![](images/(4).jpg)
 82             ![](images/(5).jpg)
 83             ![](images/(6).jpg)
 84             ![](images/(7).jpg)
 85             ![](images/(8).jpg)
 86         </div>
 87         <ul class="index">
 88             <li class="first"></li>
 89             <li></li>
 90             <li></li>
 91             <li></li>
 92             <li></li>
 93             <li></li>
 94             <li></li>
 95             <li></li>
 96         </ul>
 97         <div class="right">></div>
 98         <div class="left"><</div>
 99     </div>
100     <script type="text/javascript">
101         $(function(){
102             //每个固定的时间移动图片
103             var timer = setInterval(picLoop,1000);
104             var index = 0;
105             function picLoop(){
106                 index++;
107                 if (index==8) {index=0;}
108                 $(".content").animate({"left":-790*index},300);
109                 $("li").eq(index).css("background-color","red")
110                        .siblings().css("background-color","rgba(100,100,100,0.3)");
111             }
112 
113             //定时器的控制
114             $(".pic").hover(function(){
115                 clearInterval(timer);
116                 $(".left").show();
117                 $(".right").show();
118             },function(){
119                 timer = setInterval(picLoop,1000);
120                 $(".left").hide();
121                 $(".right").hide();
122             })
123 
124             $("li").mouseover(function(){
125                 $(this).css("background-color","red")
126                        .siblings().css("background-color","rgba(100,100,100,0.3)");
127                 index = $(this).index();
128                 $(".content").animate({"left":-790*index},300);
129 
130             })
131 
132             $(".left").click(function(){
133                 index--;
134                 if (index==-1) {index=7;}
135                 $(".content").animate({"left":-790*index},300);
136                 $("li").eq(index).css("background-color","red")
137                        .siblings().css("background-color","rgba(100,100,100,0.3)");
138             })
139             $(".right").click(function(){
140                 index++;
141                 if (index==8) {index=0}
142                 $(".content").animate({"left":-790*index},300);
143                 $("li").eq(index).css("background-color","red")
144                        .siblings().css("background-color","rgba(100,100,100,0.3)"); 
145             })
146 
147 
148         })
149     </script>
150 </body>
151 </html>

 

方式三:改变透明度实现图片轮播

将所有要轮播的图片全部定位到一起,即一层一层摞起来,并且利用层级的属性调整正确的图片顺序,将图片的透明度全部设置为0,然后在让初始的第一张图片的透明度为1即可,具体代码如下:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         html body {
  8             margin: 0;
  9             padding: 0;
 10         }
 11         li{
 12             list-style: none;
 13         }
 14         .div1{
 15             width: 500px;
 16             height: 400px;
 17             margin: 50px auto;
 18             position: relative;
 19             border: 1px solid black;
 20 
 21         }
 22         .div1 a img {
 23             width: 400px;
 24             position: absolute;
 25             margin: 118px 50px;
 26         }
 27         .div1 ul{
 28             position: absolute;
 29             bottom: 110px;
 30             right:53px;
 31             z-index: 10;
 32         }
 33         .div1 ul li {
 34             width: 15px;
 35             height: 15px;
 36             line-height: 15px;
 37             border-radius: 50%;
 38             float: left;
 39             background-color: white;
 40             margin-right: 5px;
 41             cursor: pointer;
 42             text-align: center;
 43         }
 44     </style>
 45 </head>
 46 <body>
 47 <div class="div1" id="div1">
 48     <a href="javascript:void(0)"><img src="images/1.jpg"></a>
 49     <a href="javascript:void(0)"><img src="images/2.jpg"></a>
 50     <a href="javascript:void(0)"><img src="images/3.jpg"></a>
 51     <a href="javascript:void(0)"><img src="images/4.jpg"></a>
 52     <a href="javascript:void(0)"><img src="images/5.jpg"></a>
 53     <ul>
 54         <li>1</li>
 55         <li>2</li>
 56         <li>3</li>
 57         <li>4</li>
 58         <li>5</li>
 59     </ul>
 60 </div>
 61 <script>
 62     var div1 = document.getElementById("div1");//整个区域
 63     var a1 = div1.getElementsByTagName("a");//a标签 图片
 64     var li1 = div1.getElementsByTagName("li");//右下角按钮
 65     var ab = 0; //ab的值控制触摸按钮后的下一张图
 66     //遍历所有图和按钮,页面加载完毕显示第一张图和第一个按钮
 67     window.onload = function () {
 68         for (var i=0;i<a1.length;i++){
 69             if (i!=0){
 70             a1[i].style.opacity = 0;
 71             }else {
 72                 li1[i].style.backgroundColor = "green";
 73             }
 74         }
 75     };
 76     //运行函数bb();
 77     function bb() {
 78      for (var j=0;j<li1.length;j++) {
 79          //遍历所有的按钮,所有按钮都给绑定一个鼠标移上去的onmouseover事件
 80          li1[j].onmouseover = function () {
 81              //变量index就是当前触摸的按钮的文本-1,此前特意设置按钮文本为数字
 82              var index = this.innerHTML - 1;
 83              ab = index; //ab后面用return返回
 84              //声明变量b
 85              for (var b = 0; b < li1.length; b++) {
 86                  //当b就是被触摸到的按钮的索引号时,设置第b张图片不透明度为100,渐变透明度效果1s,第b个按钮背景色变成green
 87                  if (b == index) {
 88                      a1[b].style.opacity = 100;
 89                      a1[b].style.transition = "opacity 1s";
 90                      li1[b].style.backgroundColor = "green";
 91                  } else { //当b不是被触摸到的按钮的索引号时,就变透明,按钮颜色白色.
 92                      a1[b].style.opacity = 0;
 93                      li1[b].style.backgroundColor = "white";
 94                  }
 95              }
 96              return ab; //返回ab,貌似运用到了闭包?不太了解.
 97          }
 98 
 99      }
100       setInterval(function ac() { //设置2000毫秒重复运行
101                 ab = ab>li1.length-2?0:++ab; //5张图,当触摸到的按钮索引号大于3时(比如4),那么ab=0(下一张图为第0张),否则++ab;
102          //循环遍历下一张图的效果.
103                 for (var b = 0; b < li1.length; b++) {
104                     if (b == ab) {
105                         a1[b].style.opacity = 100;
106                         a1[b].style.transition = "opacity 1s";
107                         li1[b].style.backgroundColor = "green";
108                     } else {
109                         a1[b].style.opacity = 0;
110                         li1[b].style.backgroundColor = "white";
111                     }
112                 }
113             },2000);
114     }
115     bb(); //运行bb()
116 </script>
117 </body>
118 </html>

 

 

方法四:利用层级的高低来使最顶部图片变化的做法,这个做法也没有位移的动作,每次改变图片z-index的值来控制轮播,有一点问题就是,方向可能不好控制。

代码:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>轮播图 (闪现 自适应)</title>
 6 <style media="screen">
 7 * {
 8 margin: 0;
 9 padding: 0;
10 }
11 .wrap {
12 width: 60%;
13 background: red;
14 margin: auto;
15 position: relative;
16 }
17 .wrap img {
18 width: 100%;
19 position: absolute;
20 /*z-index: 10;*/
21 }
22 input {
23 border: 1px solid lightgray;
24 width: 50px;
25 height: 30px;
26 background: red;
27 border-radius: 5px;
28 font-size: 20px;
29 }
30 </style>
31 </head>
32 <body>
33 <div class="wrap">
34 <img src="images/1.jpg" alt="" />
35 <img src="images/2.jpg" alt="" />
36 <img src="images/3.jpg" alt="" />
37 <img src="images/4.jpg" alt="" />
38 </div>
39 <input type="button" id="butLeft" name="name" value="◀︎">
40 <input type="button" id="butRight" name="name" value="▶︎">
41 </body>
42 <script type="text/javascript">
43 // 获取images元素生成字符串数组,字符串数组不能进行push pop splice 等操作
44 // 所以要将它的值重新存放进一个数组中,后面有定义
45 var images = document.getElementsByTagName('img');
46 var butLeft = document.getElementById('butLeft');
47 var butRight = document.getElementById('butRight');
48 //获取变量index 用来为后面设置层级用
49 var index = 1000;
50 // 获取一个空的数组,用来存放images里面的字符串元素
51 var imagess = [];
52 
53 // for循环用来给imagess数组赋值,并且改变数组中的元素的层级
54 for (var i = 0; i < images.length; i++) {
55 imagess[i] = images[i];
56 var currentImage = imagess[i];
57 // 当前图片的层级的设置,一轮for循环都为他们设置了初始的zIndex,图片越靠前,层级设置
58 // 要求越高,所以用的是-i,这样图片会按顺序从第一张,第二张.....依次向下
59 currentImage.style.zIndex = -i;
60 }
61 
62 
63 
64 // 设置计数器count,执行一次点击事件(向左或者向右)count加1
65 var count = 0;
66 
67 
68 // 向左的点击事件
69 butLeft.onclick = function() {
70 // 从数组头部弹出一个图片元素
71 var showFirst = imagess.shift();
72 // 给弹出的这个图片元素设置层级,即 -1000+count,
73 // 让层级相较其他元素是最小的,数组头部弹出的图片会显示在最底层
74 showFirst.style.zIndex = - index + count;
75 // 层级改变完成后再将他push进数组的尾部
76 imagess.push(showFirst);
77 // 点击一次加1,不用考虑具体的值,只需要有点击事件加 1
78 count++;
79 }
80 // 向右点击事件
81 butRight.onclick = function() {
82 // 从imagess的尾部弹出一个元素,并赋值给showFirst
83 var showFirst = imagess.pop();
84 // 设置showFirst的层级为最大,1000+count ,这样他会显示在第一层
85 showFirst.style.zIndex = index + count;
86 // 层级改变之后将他在插入数组imagess的头部
87 imagess.unshift(showFirst);
88 // 点击一次加1
89 count++;
90 }
91 </script>
92 </html>

 

方式五:将一些图片在一行中平铺,然后计算偏移量再利用定时器实现定时轮播。

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>轮播效果</title>
  6     <style>
  7         * {
  8             margin: 0;
  9             padding: 0
 10         }
 11         .box {
 12             width: 500px;
 13             height: 300px;
 14             border: 1px solid #ccc;
 15             margin: 100px auto;
 16             padding: 5px;
 17  
 18         }
 19         .inner{
 20             width: 500px;
 21             height: 300px;
 22             position: relative;
 23             overflow: hidden;
 24         }
 25         .inner img{
 26             width: 500px;
 27             height: 300px;
 28             vertical-align: top
 29         }
 30         ul {
 31             width: 1000%;
 32             position: absolute;
 33             list-style: none;
 34             left:0;
 35             top: 0;
 36         }
 37         .inner li{
 38             float: left;
 39  
 40         }
 41  
 42         ol {
 43             position: absolute;
 44             height: 20px;
 45             right: 20px;
 46             bottom: 20px;
 47             text-align: center;
 48             padding: 5px;
 49         }
 50         ol li{
 51             display: inline-block;
 52             width: 20px;
 53             height: 20px;
 54             line-height: 20px;
 55             background-color: #fff;
 56             margin: 5px;
 57             cursor: pointer;
 58  
 59         }
 60         ol .current{
 61             background-color: red;
 62         }
 63         #arr{
 64             display: none;
 65         }
 66         #arr span{
 67             width: 40px;
 68             height: 40px;
 69             position: absolute;
 70             left: 5px;
 71             top: 50%;
 72             margin-top: -20px;
 73             background: #fff;
 74             cursor: pointer;
 75             line-height: 40px;
 76             text-align: center;
 77             font-weight: bold;
 78             font-family: '黑体';
 79             font-size: 30px;
 80             color: #000;
 81             opacity: 0.5;
 82             border: 1px solid #fff;
 83         }
 84         #arr #right {
 85             right: 5px;
 86             left: auto;
 87         }
 88     </style>
 89 </head>
 90 <body>
 91 <div class="box" id="box">
 92     <div class="inner">
 93         <!--轮播图-->
 94         <ul>
 95             <li><a href="#"><img src="images/1.jpg" alt=""></a></li>
 96             <li><a href="#"><img src="images/2.jpg" alt=""></a></li>
 97             <li><a href="#"><img src="images/3.jpg" alt=""></a></li>
 98             <li><a href="#"><img src="images/4.jpg" alt=""></a></li>
 99             <li><a href="#"><img src="images/5.jpg" alt=""></a></li>
100  
101         </ul>
102  
103         <ol class="bar">
104  
105         </ol>
106         <!--左右焦点-->
107         <div id="arr">
108                     <span id="left">
109                         <
110                     </span>
111             <span id="right">
112                         >
113                     </span>
114         </div>
115  
116     </div>
117 </div>
118 <script>
119     /**
120      *
121      * @param id  传入元素的id
122      * @returns {HTMLElement | null}  返回标签对象,方便获取元素
123      */
124     function my$(id) {
125         return document.getElementById(id);
126     }
127  
128     //获取各元素,方便操作
129     var box=my$("box");
130     var inner=box.children[0];
131     var ulObj=inner.children[0];
132     var list=ulObj.children;
133     var olObj=inner.children[1];
134     var arr=my$("arr");
135     var imgWidth=inner.offsetWidth;
136     var right=my$("right");
137     var pic=0;
138     //根据li个数,创建小按钮
139     for(var i=0;i<list.length;i++){
140         var liObj=document.createElement("li");
141  
142         olObj.appendChild(liObj);
143         liObj.innerText=(i+1);
144         liObj.setAttribute("index",i);
145  
146         //为按钮注册mouseover事件
147         liObj.οnmοuseοver=function () {
148             //先清除所有按钮的样式
149  
150             for (var j=0;j<olObj.children.length;j++){
151                 olObj.children[j].removeAttribute("class");
152             }
153             this.className="current";
154             pic=this.getAttribute("index");
155             animate(ulObj,-pic*imgWidth);
156         }
157  
158     }
159  
160  
161     //设置ol中第一个li有背景颜色
162     olObj.children[0].className = "current";
163     //克隆一个ul中第一个li,加入到ul中的最后=====克隆
164     ulObj.appendChild(ulObj.children[0].cloneNode(true));
165  
166     var timeId=setInterval(onmouseclickHandle,1000);
167     //左右焦点实现点击切换图片功能
168     box.οnmοuseοver=function () {
169         arr.style.display="block";
170         clearInterval(timeId);
171     };
172     box.οnmοuseοut=function () {
173         arr.style.display="none";
174         timeId=setInterval(onmouseclickHandle,1000);
175     };
176  
177     right.οnclick=onmouseclickHandle;
178     function onmouseclickHandle() {
179         //如果pic的值是5,恰巧是ul中li的个数-1的值,此时页面显示第六个图片,而用户会认为这是第一个图,
180         //所以,如果用户再次点击按钮,用户应该看到第二个图片
181         if (pic == list.length - 1) {
182             //如何从第6个图,跳转到第一个图
183             pic = 0;//先设置pic=0
184             ulObj.style.left = 0 + "px";//把ul的位置还原成开始的默认位置
185         }
186         pic++;//立刻设置pic加1,那么此时用户就会看到第二个图片了
187         animate(ulObj, -pic * imgWidth);//pic从0的值加1之后,pic的值是1,然后ul移动出去一个图片
188         //如果pic==5说明,此时显示第6个图(内容是第一张图片),第一个小按钮有颜色,
189         if (pic == list.length - 1) {
190             //第五个按钮颜色干掉
191             olObj.children[olObj.children.length - 1].className = "";
192             //第一个按钮颜色设置上
193             olObj.children[0].className = "current";
194         } else {
195             //干掉所有的小按钮的背景颜色
196             for (var i = 0; i < olObj.children.length; i++) {
197                 olObj.children[i].removeAttribute("class");
198             }
199             olObj.children[pic].className = "current";
200         }
201     }
202     left.οnclick=function () {
203         if (pic==0){
204             pic=list.length-1;
205             ulObj.style.left=-pic*imgWidth+"px";
206         }
207         pic--;
208         animate(ulObj,-pic*imgWidth);
209         for (var i = 0; i < olObj.children.length; i++) {
210             olObj.children[i].removeAttribute("class");
211         }
212         //当前的pic索引对应的按钮设置颜色
213         olObj.children[pic].className = "current";
214     };
215  
216     //设置任意的一个元素,移动到指定的目标位置
217     function animate(element, target) {
218         clearInterval(element.timeId);
219         //定时器的id值存储到对象的一个属性中
220         element.timeId = setInterval(function () {
221             //获取元素的当前的位置,数字类型
222             var current = element.offsetLeft;
223             //每次移动的距离
224             var step = 10;
225             step = current < target ? step : -step;
226             //当前移动到位置
227             current += step;
228             if (Math.abs(current - target) > Math.abs(step)) {
229                 element.style.left = current + "px";
230             } else {
231                 //清理定时器
232                 clearInterval(element.timeId);
233                 //直接到达目标
234                 element.style.left = target + "px";
235             }
236         }, 10);
237     }
238 </script>
239 </body>
240 </html>

 

 

posted @ 2019-12-01 22:31  xiongbing  阅读(5734)  评论(0编辑  收藏  举报