jQuery實現(xiàn)輪播

一芥映、輪播的實現(xiàn)原理

1.輪播是把需要輪播的圖片浮動水平排列成一排捷枯。

2.然后設置一個視窗滚秩,大小等于一張圖片。

3.視窗的overflow設置為hidden淮捆,溢出部分不可見郁油。

4.點擊下一頁本股,所有圖片就水平移動一個寬度。

5.如果要實現(xiàn)左右滾動無限循環(huán)的效果桐腌,就需要在圖片列表開頭和結尾分別添加最后一張圖和第一張圖

就像一張膠卷拄显,每次展示一張圖片,通過移動膠卷來切換可視的圖片案站。

二躬审、使用jquery實現(xiàn)圖片自動輪播效果

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>無限循環(huán)滾動輪播</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;
    }

    /*觸發(fā)BFC,清除浮動*/
    .carousel .img-ct {
      position: absolute;
      overflow: hidden;
    }

    /*讓需要輪播的圖片水平浮動排列一排*/
    .carousel .img-ct li {
      float: left;
    }
    
    /*創(chuàng)造可視窗口承边,大小等于一個圖片的寬度,溢出部分不展示*/
    .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會出現(xiàn)縫隙問題炒刁,解決方法設置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'),
        //設置狀態(tài)鎖
        lock = false,
        //設置計時器
        clock,
        //記錄當前所在頁面
        currentIndex = 0;



    var $last = $imgCt.children("li").last().clone(),
        $first = $imgCt.children("li").first().clone();
    
    //在圖片列表開頭和結尾分別添加最后一張圖和第一張圖,這時圖片的個數(shù)變?yōu)?誊稚,而$imgLen值還是4,不是動態(tài)改變的
    $imgCt.append($first);
    $imgCt.prepend($last);

    $imgCt.css({
      //因為輪播的圖片個數(shù)可以根據(jù)需求改變罗心,所以$imgCt的寬度不應該寫死里伯,而應該動態(tài)計算
      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){
      //設置狀態(tài)鎖防止?jié)L動過程中重復點擊
      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>

效果展示

三飒箭、在自動輪播代碼的基礎上改進代碼狼电,實現(xiàn)漸變輪播效果

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>無限循環(huán)滾動輪播</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;
    }

    /*觸發(fā)BFC,清除浮動*/
    .carousel .img-ct {
      position: absolute;
      overflow: hidden;
    }

    /*讓需要輪播的圖片水平浮動排列一排*/
    .carousel .img-ct li {
      float: left;
    }
    
    /*創(chuàng)造可視窗口弦蹂,大小等于一個圖片的寬度肩碟,溢出部分不展示*/
    .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會出現(xiàn)縫隙問題凸椿,解決方法設置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'),
        //設置狀態(tài)鎖
        lock = false,
        //設置計時器
        clock,
        //記錄當前所在頁面
        currentIndex = 0;



    var $last = $imgCt.children("li").last().clone(),
        $first = $imgCt.children("li").first().clone();
    
    //在圖片列表開頭和結尾分別添加最后一張圖和第一張圖削祈,這時圖片的個數(shù)變?yōu)?,而$imgLen值還是4脑漫,不是動態(tài)改變的
    $imgCt.append($first);
    $imgCt.prepend($last);

    $imgCt.css({
      //因為輪播的圖片個數(shù)可以根據(jù)需求改變髓抑,所以$imgCt的寬度不應該寫死,而應該動態(tài)計算
      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){
      //設置狀態(tài)鎖防止?jié)L動過程中重復點擊
      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>

效果展示

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末羹饰,一起剝皮案震驚了整個濱河市伊滋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌严里,老刑警劉巖新啼,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異刹碾,居然都是意外死亡燥撞,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門迷帜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來物舒,“玉大人,你說我怎么就攤上這事戏锹」诳瑁” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵锦针,是天一觀的道長荠察。 經常有香客問我,道長奈搜,這世上最難降的妖魔是什么悉盆? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮馋吗,結果婚禮上焕盟,老公的妹妹穿的比我還像新娘。我一直安慰自己宏粤,他們只是感情好脚翘,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著绍哎,像睡著了一般来农。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蛇摸,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天备图,我揣著相機與錄音,去河邊找鬼赶袄。 笑死揽涮,一個胖子當著我的面吹牛,可吹牛的內容都是我干的饿肺。 我是一名探鬼主播蒋困,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼敬辣!你這毒婦竟也來了雪标?” 一聲冷哼從身側響起零院,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎村刨,沒想到半個月后告抄,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡嵌牺,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年打洼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片逆粹。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡募疮,死狀恐怖,靈堂內的尸體忽然破棺而出僻弹,到底是詐尸還是另有隱情阿浓,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布蹋绽,位于F島的核電站芭毙,受9級特大地震影響,放射性物質發(fā)生泄漏卸耘。R本人自食惡果不足惜稿蹲,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鹊奖。 院中可真熱鬧,春花似錦涂炎、人聲如沸忠聚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽两蟀。三九已至,卻和暖如春震缭,著一層夾襖步出監(jiān)牢的瞬間赂毯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工拣宰, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留党涕,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓巡社,卻偏偏與公主長得像膛堤,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子晌该,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內容

  • 題目1: 輪播的實現(xiàn)原理是怎樣的肥荔?如果讓你來實現(xiàn)绿渣,你會抽象出哪些函數(shù)(or接口)供使用?(比如 play()) 輪...
    蕭雪圣閱讀 469評論 0 1
  • 題目1:輪播的實現(xiàn)原理是怎樣的燕耿?如果讓你來實現(xiàn)中符,你會抽象出哪些函數(shù)(or接口)供使用?(比如 play()) 布局...
    阿魯提爾閱讀 520評論 0 2
  • HTML部分: CSS部分: JQuery部分: 效果圖:
    BugLuv閱讀 290評論 0 0
  • Day1 機會成本的前提是稀缺性(特別是時間的稀缺性) Day2 實際上誉帅,在我們對世界的觀察當中充滿了理論淀散,我們才...
    Rutona閱讀 206評論 0 0
  • 一、相對論怪圈之誘餌效應: lA,-A,B堵第,三個選擇當中吧凉,-A明顯是作為誘餌,建構出與A的一種簡單踏志,直觀的比較關系...
    crazyyoyo閱讀 745評論 0 3