js轮播图无缝滚动效果

在做轮播图时如果首尾不能连起来的话,效果会有点丑,下面介绍一种我常用的方法:

先文字说明一下:

如果要展示5张图,分别为1,2,3,4,5  那么在代码的引入中是这样的:1,2,3,4,5,1

按顺序的轮播在此就不多说,重点说的是5>1和1>5的轮播

i  表示当前图片的索引

pre 表示上一张图片的按钮

next 表示下一张图片的按钮

ul 表示图片列表

(1)  5>1>2...   当“next”按钮从5到1时按顺序正常轮播,当前图片为第二个“1”时,下一张图片应该是“2”,那么再“next”时是ul的left的值为0,i==1;

(2) 1>5>4....  当“pre”按钮从当前图片“1”(第一个1)轮播到图片5时,i==4,ul的left值变为img宽的-5倍,也就是让第一个1悄悄的变为最后一个1;

用语言表述有点乱,下面放代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{padding: 0;margin: 0;} .container{ width: 273px;height: 163px;overflow: hidden; position: relative;margin: 0 auto; } .list{ position: absolute;width: 1638px;top: 0;left: 0px; } .list li{ float: left;list-style: none; } .btn{ position: absolute;display: block;width: 40px;height: 50px;font-size: 40px; text-align: center;font-weight: bold;top: 50%;margin-top: -25px;background-color: rgba(255,255,255,0.5);cursor:pointer; } .btn:hover{ background-color: rgba(0,0,0,0.3);color: #fff; } .pre{ left: 0; } .next{ right: 0; } .nav{ position: absolute;bottom: 5px;display: flex;justify-content: center;width: 100%; } .nav span{ width: 10px;height: 10px;border-radius: 10px;background-color: #fff;z-index: 2;display: inline-block;margin-right: 10px;cursor: pointer; } span.on{ background-color: orange; } </style> </head> <body> <div> <ul> <li><img src="https://www.jb51.net/article/images/1.png" alt=""></li> <li><img src="https://www.jb51.net/article/images/2.png" alt=""></li> <li><img src="https://www.jb51.net/article/images/3.png" alt=""></li> <li><img src="https://www.jb51.net/article/images/4.png" alt=""></li> <li><img src="https://www.jb51.net/article/images/5.png" alt=""></li> <li><img src="https://www.jb51.net/article/images/1.png" alt=""></li> </ul> <div> <span></span> <span></span> <span></span> <span></span> <span></span> </div> <em>></em> <em><</em> </div> <script type="text/javascript" src="https://www.jb51.net/jquery.js"></script> <script type="text/javascript"> $(function(){ var i=0; $('.next').click(function(){ i++; console.log(i); moveImg(i); }); $('.pre').click(function(){ i--; moveImg(i); }); $('.nav span').click(function(){ var _index=$(this).index(); i=_index; moveImg(i); }); // i的作用:决定下一张图片是谁————也就是说ul的left是多少。 // $('.list').css({left)的值是从图a过度是此时的ul的left。 function moveImg(){ if (i==6) { i=1; $('.list').css({'left':'0'}); } // 是第一张 if(i==-1){ i=4; $('ul').css({left:(5*-273)}); } $('.list').stop().animate({'left':-273*i+'px'},1000); if (i==5) { $('.nav span').eq(0).addClass('on').siblings().removeClass('on'); } $('.nav span').eq(i).addClass('on').siblings().removeClass('on'); } }) </script> </body> </html>

精彩专题分享:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyxwgf.html