DIV CSS 佈局教程網

純 jQuery 圖片輪播:主圖搭配縮圖導覽
編輯:JQuery常見問題     

效果說明

主視覺輪播加上底部縮圖列,是電商首頁最經典的版型。這個範例不依賴任何外掛,只用 jQuery 就完成了自動輪播、縮圖切換與滑入動畫。

查看效果:https:///keleyi/phtml/jqtexiao/27.htm

CSS:把縮圖藏起來,滑入時再推出

.keleyiBanner{width:782px;height:326px;overflow:hidden;margin:0 auto;position:relative;}
.keleyiBanner .mask{
  height:32px;line-height:32px;background-color:#000;width:100%;text-align:right;
  position:absolute;left:0;bottom:-32px;   /* 先藏在容器外 */
  filter:alpha(opacity=70);-moz-opacity:0.7;opacity:0.7;overflow:hidden;
}
.keleyiBanner .mask img{vertical-align:middle;margin-right:10px;cursor:pointer;border:0px;}
.keleyiBanner .mask img.show{margin-bottom:3px;border:0px;}  /* 當前項的樣式 */

HTML:把大圖網址寫在自訂屬性上

縮圖上掛了兩個自訂屬性:uri 是對應的大圖路徑,link 是點擊後要跳的網址。這種「資料與 DOM 並存」的做法,讓 JavaScript 不必維護另一份對照表。

<div class="keleyiBanner">
 <a href=""><img class="bigImg" width="782" height="326" style="border:0px" /></a>
 <div class="mask">
  <img src="27/11.jpg" uri="27/11.jpg" link="/a/bjad/von5fgtg.htm" width="60" height="22"/>
  <img src="27/22.jpg" uri="27/22.jpg" link="/a/bjad/an41m07r.htm" width="60" height="22"/>
  <!-- 其餘縮圖省略 -->
 </div>
</div>

JavaScript 核心邏輯

$(function () {
  $(".keleyiBanner").each(function () {
    var timer;

    // 點縮圖切換
    $(".keleyiBanner .mask img").click(function () {
      var index = $(".keleyiBanner .mask img").index($(this));
      changeImg(index);
    }).eq(0).click();   // 觸發一次,初始化第一張

    // 縮圖列滑入
    $(this).find(".mask").animate({ "bottom": "0" }, 700);

    // 滑鼠移入暫停、移出恢復自動輪播
    $(".keleyiBanner").hover(function () {
      clearInterval(timer);
    }, function () {
      timer = setInterval(autoNext, 3000);
    });

    function changeImg(index) {
      $(".keleyiBanner .mask img").removeClass("show").eq(index).addClass("show");
      $(".keleyiBanner .bigImg").parents("a")
        .attr("href", $(".keleyiBanner .mask img").eq(index).attr("link"));
      $(".keleyiBanner .bigImg").hide()
        .attr("src", $(".keleyiBanner .mask img").eq(index).attr("uri"))
        .fadeIn("slow");
    }

    function autoNext() {
      var show = $(".keleyiBanner .mask img.show").index();
      show = (show >= $(".keleyiBanner .mask img").length - 1) ? 0 : show + 1;
      changeImg(show);
    }

    timer = setInterval(autoNext, 3000);
  });
});

幾個值得學的細節

  • .eq(0).click() 觸發初始化。不必重複寫一次首圖設定,直接觸發第一次點擊即可,程式碼更少也避免兩處邏輯不同步。
  • hide() 再 fadeIn()。確保每次切換都有淡入過渡,即使切到同一張也會重播。
  • hover 中斷計時器。使用者正在看內容時不該被強制切走,這是輪播的基本禮貌。
  • 用 .show 這組 class 記錄當前索引。不必額外維護變數,狀態直接反映在 DOM 上。

若要進一步優化,可加上 document.hidden 判斷,在分頁切到背景時暫停輪播,省下不必要的動畫運算。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved