萬盛學電腦網

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

jQuery 多屏圖層切換:縮略圖導航與自動輪播綜合實例

效果預覽

本範例實現一款功能完整的多圖層切換元件,包含:

  • 水平滑動切換四張大圖
  • 底部圓點指示器同步高亮
  • 左右箭頭按鈕控制上一張/下一張
  • 自動輪播(2 秒間隔)+ 滑鼠懸停暫停
  • 無縫循環:最後一張切下一張回到第一張

HTML 結構拆解

<div class="Xing_focus" id="box">
  <ul class="imgs" id="actor">
    <li class="list1"><img src="img1.jpg" /></li>
    <li class="list2"><img src="img2.jpg" /></li>
    <li class="list3"><img src="img3.jpg" /></li>
    <li class="list4"><img src="img4.jpg" /></li>
  </ul>
  <ul class="bnt" id="bnt"><!-- 動態生成圓點 --></ul>
  <div class="pre" id="pre">上一張</div>
  <div class="next" id="next">下一張</div>
</div>

核心 JavaScript 邏輯深度解析

$(window).on("load", function() {
  // 1. 變數初始化
  var $box = $("#box");
  var $actor = $("#actor");
  var $bnt = $("#bnt");
  var $pre = $("#pre");
  var $next = $("#next");
  
  var liWidth = $actor.find("li:first").outerWidth(true); // 含 margin
  var liCount = $actor.find("li").length;
  var currentIndex = 0;
  var isAnimating = false;
  var autoTimer;

  // 2. 動態生成圓點指示器
  for (var i = 0; i < liCount; i++) {
    $bnt.append("<li></li>");
  }
  $bnt.find("li:first").addClass("sli"); // 首個高亮

  // 3. 核心切換函數
  function slideTo(targetIndex) {
    if (isAnimating) return;
    isAnimating = true;

    // 無縫循環邏輯
    if (targetIndex >= liCount) targetIndex = 0;
    if (targetIndex < 0) targetIndex = liCount - 1;

    var targetLeft = -targetIndex * liWidth;

    $actor.animate({ marginLeft: targetLeft + "px" }, 500, function() {
      currentIndex = targetIndex;
      updateDots();
      isAnimating = false;
    });
  }

  function updateDots() {
    $bnt.find("li").removeClass("sli").eq(currentIndex).addClass("sli");
  }

  // 4. 事件綁定
  $bnt.on("click", "li", function() {
    var idx = $(this).index();
    if (idx !== currentIndex) slideTo(idx);
  });

  $next.on("click", function() { slideTo(currentIndex + 1); });
  $pre.on("click", function() { slideTo(currentIndex - 1); });

  // 5. 自動輪播
  function startAuto() {
    autoTimer = setInterval(function() { slideTo(currentIndex + 1); }, 2000);
  }
  function stopAuto() { clearInterval(autoTimer); }

  $box.hover(stopAuto, startAuto);
  startAuto();
});

CSS 佈局要點

.Xing_focus {
  width: 875px;
  height: 500px; /* 修正原始碼 800px 過高問題 */
  overflow: hidden;
  position: relative;
  border: 1px solid red;
  margin: 0 auto;
}
.imgs {
  width: 3500px; /* 875px * 4 */
  position: relative;
  left: 0;
  transition: margin-left 0.5s ease; /* 可選:CSS 動畫替代 jQuery animate */
}
.imgs li {
  float: left;
  width: 875px;
  height: 500px;
}
.bnt {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}
.bnt li {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: red;
  margin: 0 6px;
  cursor: pointer;
}
.bnt li.sli { background: blue; }
.pre, .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background: rgba(0,0,0,0.5);
  color: #fff;
  text-align: center;
  line-height: 40px;
  cursor: pointer;
  z-index: 10;
  border-radius: 50%;
}
.pre { left: 20px; }
.next { right: 20px; }

常見坑點與修正

問題原因修正
圖片載入前寬度為 0$(document).ready 觸發時圖片未載入改用 $(window).on("load") 或圖片 onload 回調
快速點擊導致動畫紊亂未檢查 :animated 狀態引入 isAnimating 旗標或 .stop(true, true)
最後一張跳回第一張有明顯位移marginLeft 直接歸零而非無縫銜接複製首張圖片置於末尾,動畫完成後瞬間重置 marginLeft
圓點數量與圖片不符迴圈邊界條件錯誤使用 liCount 變數統一控制

進階擴充:響應式與無障礙

// 響應式:視窗縮放時重新計算寬度
$(window).on("resize", function() {
  liWidth = $actor.find("li:first").outerWidth(true);
  $actor.css({ marginLeft: -currentIndex * liWidth });
});

// 鍵盤操作
$(document).on("keydown", function(e) {
  if (e.key === "ArrowLeft") $pre.click();
  if (e.key === "ArrowRight") $next.click();
});

// ARIA 無障礙屬性
$box.attr({ "role": "region", "aria-roledescription": "輪播", "aria-label": "產品展示" });
$pre.attr({ "aria-label": "上一張", "role": "button", "tabindex": "0" });
$next.attr({ "aria-label": "下一張", "role": "button", "tabindex": "0" });
$bnt.find("li").attr({ "role": "tab", "aria-selected": "false", "tabindex": "0" })
  .eq(0).attr("aria-selected", "true");

總結

此範例涵蓋了輪播元件的核心功能:狀態管理、動畫控制、事件委派、自動播放與無障礙。實務開發中,建議將邏輯封裝為可複用的 jQuery Plugin 或 ES6 Class,支援多實例、配置選項(動畫速度、自動播放間隔、循環模式、觸控支援),並搭配 CSS Transition 取代 jQuery animate 以提升效能。

copyright © 萬盛學電腦網 all rights reserved