前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >jQuery实现轮播

jQuery实现轮播

作者头像
小胖
发布2018-06-27 17:50:03
9.3K0
发布2018-06-27 17:50:03
举报

一、轮播的实现原理

1.轮播是把需要轮播的图片浮动水平排列成一排。 2.然后设置一个视窗,大小等于一张图片。 3.视窗的overflow设置为hidden,溢出部分不可见。 4.点击下一页,所有图片就水平移动一个宽度。 5.如果要实现左右滚动无限循环的效果,就需要在图片列表开头和结尾分别添加最后一张图和第一张图

就像一张胶卷,每次展示一张图片,通过移动胶卷来切换可视的图片。

二、使用jquery实现图片自动轮播效果

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>无限循环滚动轮播</title>
  <style>
    .carousel {
      margin: 0 auto;
      margin-top: 200px;
    }
    .carousel ul,
    .carousel li {
      margin: 0;
      padding: 0;
      list-style: none;
    }
    
    .carousel .img-ct img {
      width: 400px;
      height: 250px;
    }

    /*触发BFC,清除浮动*/
    .carousel .img-ct {
      position: absolute;
      overflow: hidden;
    }

    /*让需要轮播的图片水平浮动排列一排*/
    .carousel .img-ct li {
      float: left;
    }
    
    /*创造可视窗口,大小等于一个图片的宽度,溢出部分不展示*/
    .carousel {
      position: relative;
      width: 400px;
      height: 250px;
      overflow: hidden;
    }
    
    /*设置左右播放按钮的样式*/
    .carousel .arrow {
      position: absolute;
      top: 50%;
      margin-top: -15px;
      display: inline-block;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      border: 2px solid #fff;
      line-height: 30px;
      font-weight: bold;
      color: #fff;
      text-align: center;
      text-decoration: none;
    }
    .carousel .arrow:hover {
      opacity: 0.7;
    }
    .carousel .pre {
      left: 10px;
    }
    .carousel .next {
      right: 10px;
    }
    
    /*设置图片上的四个小按钮*/
    .carousel .bullet {
      position: absolute;
      width: 100%;
      /*子元素不是浮动元素,不用设置高度*/
      bottom: 10px;
      text-align: center;
    }
    .carousel .bullet >li {
      display: inline-block;
      width: 30px;
      height: 5px;
      border: 1px solid #ccc;
      border-radius: 4px;
      cursor: pointer;
      /*设置inline-block会出现缝隙问题,解决方法设置font-size: 0;*/
      font-size: 0;
    }
    .carousel .bullet >li.active {
      background-color: #ccc;
    }
  </style>
</head>
<body>
  <div class="carousel">
    <ul class="img-ct">
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-de9e5f9191b7173c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-8614362c64c4ac1c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-fc558baf8b53a5c7.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-3ceb510fedaa85c8.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
    </ul>
    <a href="#" class="pre arrow"><</a>
    <a href="#" class="next arrow">></a>
    <ul class="bullet">
      <li class="active"></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <script src="https://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
  <script>
    var $imgCt = $('.img-ct'),
        $imgWidth = $('.carousel .img-ct >li').eq(0).width(),
        $imgLen = $('.carousel .img-ct >li').length,
        $preBtn = $('.carousel .pre'),
        $nextBtn = $('.carousel .next'),
        $bullet = $('.bullet li'),
        //设置状态锁
        lock = false,
        //设置计时器
        clock,
        //记录当前所在页面
        currentIndex = 0;



    var $last = $imgCt.children("li").last().clone(),
        $first = $imgCt.children("li").first().clone();
    
    //在图片列表开头和结尾分别添加最后一张图和第一张图,这时图片的个数变为6,而$imgLen值还是4,不是动态改变的
    $imgCt.append($first);
    $imgCt.prepend($last);

    $imgCt.css({
      //因为轮播的图片个数可以根据需求改变,所以$imgCt的宽度不应该写死,而应该动态计算
      width: $imgWidth*($imgLen+2),
      left: -$imgWidth
    })


    $preBtn.on('click',function(){
      playPre(1);
    })
    $nextBtn.on('click',function(){
      playNext(1);
    })

    timeClock();

    //当鼠标在图片上停留时,停止自动轮播
    $(".carousel").on("mouseenter",function(){
        clearInterval(clock)
    })
    //当鼠标离开时,开始自动轮播
    $(".carousel").on("mouseleave",function(){
        timeClock()
    })

    function playNext(len){
      //设置状态锁防止滚动过程中重复点击
      if(lock){
        return;
      }
      lock = true
      $imgCt.animate({
        left: '-='+len*$imgWidth
      },function(){
        currentIndex+=len;
        if (currentIndex === $imgLen) {
          currentIndex = 0;
          $imgCt.css({left: -$imgWidth})
        }
        setBullet();
        lock = false;
      })
    }
    function playPre(len){
      if(lock){
        return;
      }
      lock = true
      $imgCt.animate({
        left: '+='+len*$imgWidth
      },function(){
        currentIndex-=len;
        if (currentIndex === -1) {
          currentIndex = $imgLen-1;
          $imgCt.css({left: -$imgLen*$imgWidth})
        }
        //当滚动到某个图片时,为其对应的小按钮设置样式
        setBullet();
        lock = false;
      })
    }

    //点击小按钮滚动到对应图片上
    $bullet.on('click',function(){
      var index = $(this).index();
      if(index > currentIndex){
        playNext(index - currentIndex)
      }else if(index < currentIndex){
        playPre(currentIndex - index);
      }
    })

    function setBullet(){
      $bullet.removeClass('active')
             .eq(currentIndex)
             .addClass('active')
    }

    //自动轮播,每个一秒滚动一次
    function timeClock(){
      clock = setInterval(function(){
         playNext(1)
       },1000)
    }
  </script>
</body>
</html>

效果展示

三、在自动轮播代码的基础上改进代码,实现渐变轮播效果

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>无限循环滚动轮播</title>
  <style>
    .carousel {
      margin: 0 auto;
      margin-top: 200px;
    }
    .carousel ul,
    .carousel li {
      margin: 0;
      padding: 0;
      list-style: none;
    }
    
    .carousel .img-ct img {
      width: 400px;
      height: 250px;
    }

    /*触发BFC,清除浮动*/
    .carousel .img-ct {
      position: absolute;
      overflow: hidden;
    }

    /*让需要轮播的图片水平浮动排列一排*/
    .carousel .img-ct li {
      float: left;
    }
    
    /*创造可视窗口,大小等于一个图片的宽度,溢出部分不展示*/
    .carousel {
      position: relative;
      width: 400px;
      height: 250px;
      overflow: hidden;
    }
    
    /*设置左右播放按钮的样式*/
    .carousel .arrow {
      position: absolute;
      top: 50%;
      margin-top: -15px;
      display: inline-block;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      border: 2px solid #fff;
      line-height: 30px;
      font-weight: bold;
      color: #fff;
      text-align: center;
      text-decoration: none;
    }
    .carousel .arrow:hover {
      opacity: 0.7;
    }
    .carousel .pre {
      left: 10px;
    }
    .carousel .next {
      right: 10px;
    }
    
    /*设置图片上的四个小按钮*/
    .carousel .bullet {
      position: absolute;
      width: 100%;
      /*子元素不是浮动元素,不用设置高度*/
      bottom: 10px;
      text-align: center;
    }
    .carousel .bullet >li {
      display: inline-block;
      width: 30px;
      height: 5px;
      border: 1px solid #ccc;
      border-radius: 4px;
      cursor: pointer;
      /*设置inline-block会出现缝隙问题,解决方法设置font-size: 0;*/
      font-size: 0;
    }
    .carousel .bullet >li.active {
      background-color: #ccc;
    }
  </style>
</head>
<body>
  <div class="carousel">
    <ul class="img-ct">
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-cfc32cb79ef01739.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-25860355b0862774.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-be4729b225df4e45.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
      <li><a href="javascript:void(0)">![图片加载失败](http://upload-images.jianshu.io/upload_images/1969310-aa0ed1f379f33f06.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
    </ul>
    <a href="#" class="pre arrow"><</a>
    <a href="#" class="next arrow">></a>
    <ul class="bullet">
      <li class="active"></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <script src="https://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
  <script>
    var $imgCt = $('.img-ct'),
        $imgWidth = $('.carousel .img-ct >li').eq(0).width(),
        $imgLen = $('.carousel .img-ct >li').length,
        $preBtn = $('.carousel .pre'),
        $nextBtn = $('.carousel .next'),
        $bullet = $('.bullet li'),
        //设置状态锁
        lock = false,
        //设置计时器
        clock,
        //记录当前所在页面
        currentIndex = 0;



    var $last = $imgCt.children("li").last().clone(),
        $first = $imgCt.children("li").first().clone();
    
    //在图片列表开头和结尾分别添加最后一张图和第一张图,这时图片的个数变为6,而$imgLen值还是4,不是动态改变的
    $imgCt.append($first);
    $imgCt.prepend($last);

    $imgCt.css({
      //因为轮播的图片个数可以根据需求改变,所以$imgCt的宽度不应该写死,而应该动态计算
      width: $imgWidth*($imgLen+2),
      left: -$imgWidth
    })


    $preBtn.on('click',function(){
      playPre(1);
    })
    $nextBtn.on('click',function(){
      playNext(1);
    })

    timeClock();

    //当鼠标在图片上停留时,停止自动轮播
    $(".carousel").on("mouseenter",function(){
        clearInterval(clock)
    })
    //当鼠标离开时,开始自动轮播
    $(".carousel").on("mouseleave",function(){
        timeClock()
    })

    function playNext(len){
      //设置状态锁防止滚动过程中重复点击
      if(lock){
        return;
      }
      lock = true
      //当前图片淡出
      $imgCt.fadeOut(200,function(){
        currentIndex+=len;
      })
      $imgCt.fadeIn(200,function(){
        if (currentIndex === $imgLen) {
          $imgCt.css({left: -$imgWidth});
          currentIndex = 0;
        }
        setBullet();
        lock = false;
      })
      /*
      $imgCt.animate({
        left: '-='+len*$imgWidth
      },function(){
        currentIndex+=len;
        if (currentIndex === $imgLen) {
          currentIndex = 0;
          $imgCt.css({left: -$imgWidth})
        }
      })
      */
    }
    function playPre(len){
      if(lock){
        return;
      }
      lock = true;
      $imgCt.fadeOut(200,function(){
        currentIndex -= len;
      })
      $imgCt.fadeIn(200,function(){
        if (currentIndex === -1) {
          $imgCt.css({left: -$imgLen*$imgWidth});
          currentIndex = $imgLen-1;
        }
        setBullet();
        lock = false;
      })
      /*
      $imgCt.animate({
        left: '+='+len*$imgWidth
      },function(){
        currentIndex-=len;
        if (currentIndex === -1) {
          currentIndex = $imgLen-1;
          $imgCt.css({left: -$imgLen*$imgWidth})
        }
        当滚动到某个图片时,为其对应的小按钮设置样式
        setBullet();
        lock = false;
      })
      */
    }

    //点击小按钮滚动到对应图片上
    $bullet.on('click',function(){
      var index = $(this).index();
      if(index > currentIndex){
        playNext(index - currentIndex)
      }else if(index < currentIndex){
        playPre(currentIndex - index);
      }
    })

    function setBullet(){
      $bullet.removeClass('active')
             .eq(currentIndex)
             .addClass('active')
    }

    //自动轮播,每个一秒滚动一次
    function timeClock(){
      clock = setInterval(function(){
         playNext(1)
       },2000)
    }
  </script>
</body>
</html>

效果展示

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.10.12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、轮播的实现原理
  • 二、使用jquery实现图片自动轮播效果
  • 三、在自动轮播代码的基础上改进代码,实现渐变轮播效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档