萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現首頁圖片輪播淡入淡出效果:當當網品牌館實戰拆解

拆解當當網品牌館首頁輪播效果:綠色半透明標題區疊加於圖片上方,滑鼠移至標籤切換對應圖片,三張大圖自動輪播淡入淡出。

HTML 結構

<div id="carousel">
  <div id="carouselimg" class="content_top">
    <div id="imgcontainer" class="slide_panel">
      <a href="..."><img src="images/band_lx_717x280.gif" /></a>
      <a href="..."><img src="images/band_agz_717x280.gif" /></a>
      <a href="..."><img src="images/band_qb_717x280.gif" /></a>
    </div>
  </div>
  <div id="carouseltitle">
    <ul>
      <li><a href="#">聯想 <span>lenovo</span></a></li>
      <li><a href="#">愛國者 <span>aigo</span></a></li>
      <li><a href="#">倩碧 <span>CLINIQUE</span></a></li>
    </ul>
  </div>
</div>

核心 CSS 佈局與樣式

#carousel { position: relative; border: 1px solid #DFDFDF; border-top: none; }
#carouselimg { position: relative; overflow: hidden; height: 280px; }
#imgcontainer { position: absolute; left: 0; top: 0; width: 2151px; } /* 3張圖寬度總和 */
#imgcontainer img { float: left; border: 0; }

#carouseltitle { position: absolute; bottom: 0; z-index: 10; }
#carouseltitle li {
  float: left; width: 239px; height: 30px; line-height: 30px;
  text-align: center; font-size: 14px; background: #000; color: #FFF;
  cursor: pointer; opacity: .6; filter: alpha(opacity=60);
}
#carouseltitle li.active { background: #cfaf73; opacity: .9; filter: alpha(opacity=90); }
#carouseltitle li.active a { color: #000; }
#carouseltitle a { text-decoration: none; color: #fff; }
#carouseltitle a span { font-family: Arial; }

jQuery 輪播邏輯

(function($) {
  $.fn.carousel = function(options) {
    var opts = $.extend({ interval: 3000, fadeSpeed: 500 }, options);
    return this.each(function() {
      var $this = $(this);
      var $imgs = $this.find('#imgcontainer img');
      var $titles = $this.find('#carouseltitle li');
      var index = 0, timer;

      function show(idx) {
        $imgs.stop(true, true).fadeOut(opts.fadeSpeed).eq(idx).fadeIn(opts.fadeSpeed);
        $titles.removeClass('active').eq(idx).addClass('active');
      }

      function auto() {
        timer = setInterval(function() {
          index = (index + 1) % $imgs.length;
          show(index);
        }, opts.interval);
      }

      $titles.hover(function() {
        clearInterval(timer);
        index = $titles.index(this);
        show(index);
      }, function() { auto(); });

      auto(); // 啟動
    });
  };
})(jQuery);

// 初始化
$('#carousel').carousel({ interval: 4000, fadeSpeed: 600 });

關鍵技術點

  • 絕對定位容器: #imgcontainer 寬度 = 單圖寬度 × 圖片數,float:left 排列
  • 標題疊加: position:absolute; bottom:0; z-index:10 置於圖片上方
  • 半透明效果: opacity + IE filter:alpha 相容
  • 動畫佇列控制: .stop(true,true) 清除佇列並跳至終狀態,避免快速滑鼠移動造成動畫堆疊
  • 滑鼠懸停暫停: hover 進入清除定時器,離開重啟

現代化改寫建議

  • 使用 CSS transition: opacity 0.5s 替代 jQuery fadeIn/Out,效能更佳
  • 採用 IntersectionObserver 實現進入視口才啟動輪播
  • 無障礙:加入 aria-label、鍵盤焦點控制、prefers-reduced-motion 媒體查詢停用動畫
copyright © 萬盛學電腦網 all rights reserved