萬盛學電腦網

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

jQuery 仿百度經驗滑動切換瀏覽效果完整實作解析

jQuery 實現百度經驗式全屏滑動切換效果深度解析

百度經驗風格的全屏水平滑動切換是內容展示型網站的經典交互模式。本文深度解析其核心實作邏輯:動態寬度計算、左右導航控制、底部指示器同步、首字母放大動畫、邊界檢測與平滑定位。

核心架構設計

  • 容器結構:外層固定寬高 overflow:hidden,內層 ul 總寬 = 單頁寬 × 頁數
  • 導航控制:左右箭頭 + 底部指示器點點,雙重操作入口
  • 狀態管理:showId 記錄當前頁索引,attr('showId') 持久化於容器
  • 動畫引擎:.animate({left: -width * index}) 實現平滑位移

完整程式碼重構與註解


$(function() {
  // 1. 初始化佈局
  initLayout();
  
  // 2. 綁定導航事件
  bindNavigation();
  
  // 3. 產生底部指示器
  generateIndicators();
  
  // 4. 初始定位
  center(0);
  
  // 5. 文字首字母放大效果
  wordStrong();
});

function initLayout() {
  var $content = $('#content');
  var $ul = $content.find('ul');
  var $lis = $ul.find('li');
  var liWidth = $lis.first().width();
  
  // 關鍵:設定 ul 總寬度 = 單頁寬 × 頁數
  $ul.width(liWidth * $lis.length);
  
  // 左右側邊區域寬度 = (視口寬 - 內容寬) / 4
  var sideWidth = ($(document).width() - $content.width()) / 4;
  $content.find('.left, .right').width(sideWidth);
  
  // 初始隱藏側邊區域 (負定位移出視口)
  $content.find('.left').css('left', -sideWidth);
  $content.find('.right').css('right', -sideWidth);
}

function bindNavigation() {
  var $content = $('#content');
  var $leftBtn = $content.find('span.left');
  var $rightBtn = $content.find('span.right');
  var totalPages = $content.find('ul li').length;
  
  // 左箭頭:hover 顯示半透明、click 切換上一頁
  $leftBtn.hover(
    function() { 
      if (checkFirst()) return;
      $(this).css('cursor', 'pointer');
      $(this).siblings('.sl').stop().animate({opacity: 0.5});
    },
    function() { $(this).siblings('.sl').stop().animate({opacity: 0}); }
  ).click(function() {
    if (checkFirst()) return;
    navigate(-1);
  });
  
  // 右箭頭:邏輯對稱
  $rightBtn.hover(
    function() { 
      if (checkLast()) return;
      $(this).css('cursor', 'pointer');
      $(this).siblings('.sr').stop().animate({opacity: 0.5});
    },
    function() { $(this).siblings('.sr').stop().animate({opacity: 0}); }
  ).click(function() {
    if (checkLast()) return;
    navigate(1);
  });
  
  // 邊界檢測
  function checkFirst() {
    if ($content.attr('showId') == 0) {
      $leftBtn.css('cursor', 'default');
      return true;
    }
    return false;
  }
  
  function checkLast() {
    if ($content.attr('showId') == totalPages - 1) {
      $rightBtn.css('cursor', 'default');
      return true;
    }
    return false;
  }
  
  // 核心導航邏輯
  function navigate(delta) {
    var showId = parseInt($content.attr('showId')) + delta;
    $content.attr('showId', showId);
    
    // 同步底部指示器
    $('#footer li').children().removeClass('active')
      .end().children().eq(showId).addClass('active');
    
    // 執行滑動動畫
    center(showId);
  }
}

function center(liIndex) {
  var $ul = $('#content ul');
  var $li = $ul.find('li').eq(liIndex);
  var liWidth = $li.width();
  
  // 視覺反饋:當前頁不透明,其他半透明
  $ul.find('li').css('opacity', 0.3);
  $li.css('opacity', 1);
  
  // 平滑滑動
  $ul.animate({ left: -liWidth * liIndex });
}

function generateIndicators() {
  var $content = $('#content');
  var $footer = $('#footer ul');
  var totalPages = $content.find('ul li').length;
  
  // 動態生成指示器 (跳過首尾預留項)
  for (var i = 1; i < totalPages - 1; i++) {
    $('
  • ' + i + '
  • ') .insertBefore($footer.children('[step="last"]')); } // 設定首尾 step 屬性 $footer.children(':first').attr('step', 0); $footer.children(':last').attr('step', totalPages - 1); // 指示器置中 $footer.css('left', ($(window).width() - $footer.width()) / 2); // 指示器點擊事件 $('#footer li').click(function() { $('#footer li').children().removeClass('active'); $(this).children().addClass('active'); center($(this).attr('step')); }); } // 首字母放大動畫效果 function wordStrong() { $('#content ul li').each(function(liIndex) { var $paragraphs = $(this).find('.cont_word p'); $paragraphs.each(function(pIndex) { var $p = $(this); var text = $p.html(); if (!text) return; var firstChar = text.charAt(0); var restText = text.substring(1); $p.html(''); // 清空 $('').text(firstChar).css('font-size', '24px').appendTo($p); $p.append(restText); }); }); } // 跨瀏覽器事件綁定補丁 (片段) function myAddEvent(obj, e, fn) { if (obj.attachEvent) { obj.attachEvent('on' + e, fn); } else { obj.addEventListener(e, fn, false); } }

    關鍵技術難點解析

    1. 動態寬度計算時機

    必須在圖片/字體載入完成後執行 initLayout(),否則 .width() 會取得 0 或錯誤值。建議用 $(window).on('load') 或圖片 onload 回呼。

    2. 動畫隊列管理

    使用 .stop() 防止快速點擊導致動畫堆疊:

    
    $ul.stop(true, true).animate({ left: -liWidth * index });
    // stop(clearQueue, jumpToEnd): 清除隊列、跳至終點
    

    3. 指示器與內容同步

    採用單一事實來源:$content.attr('showId') 為唯一狀態,所有 UI (箭頭、指示器、內容位置) 皆由此衍生。

    4. 首字母放大實作細節

    將首字元包裹在 <b> 標籤並設定較大 font-size,利用行內元素特性自然排版,無需複雜定位。

    現代化重構方向 (Vue/React/原生)

    CSS Scroll Snap 方案 (零 JS 核心邏輯)

    
    /* CSS Only 滑動切換 */
    .slider {
      display: flex;
      overflow-x: auto;
      scroll-snap-type: x mandatory;
      -webkit-overflow-scrolling: touch;
    }
    
    .slide {
      flex: 0 0 100%;
      width: 100%;
      scroll-snap-align: start;
    }
    
    /* 指示器同步需少量 JS: IntersectionObserver */
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          updateIndicator(entry.target.dataset.index);
        }
      });
    }, { threshold: 0.5, root: document.querySelector('.slider') });
    
    document.querySelectorAll('.slide').forEach(slide => observer.observe(slide));
    

    Vue 3 Composition API 封裝

    
    
    
    
    

    無障礙與體驗增強清單

    • [ ] 鍵盤操作:左/右鍵切換、Home/End 跳首尾
    • [ ] 觸控滑動:原生 scroll + snap 或 Touch Events
    • [ ] 自動播放:可暫停、滑鼠懸停暫停、可見區域才播放
    • [ ] 減少動畫:@media (prefers-reduced-motion) 停用動畫
    • [ ] 螢幕閱讀器:aria-roledescription="slide"、aria-live
    • [ ] 指示器:role="tablist"、按鈕 role="tab"、aria-selected
    copyright © 萬盛學電腦網 all rights reserved