萬盛學電腦網

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

jQuery 自定義滾動條插件 mCustomScrollbar 完整示例與應用指南

前言

在 Web 開發中,原生瀏覽器滾動條樣式單一且難以自定義。mCustomScrollbar 是一款功能強大的 jQuery 滾動條插件,支援垂直/水平滾動、滾動條拖拽、鍵盤控制、滑鼠滾輪、觸控設備等,並提供豐富的主題與回調介面。本文將通過完整代碼示例,詳細講解如何快速集成並客製化這款插件。

核心依賴與引入

使用前需引入以下資源(建議使用本地檔案以提高穩定性):

  • jquery.mCustomScrollbar.css — 樣式表
  • jquery.min.js (≥1.4)
  • jquery-ui.min.js (含 Widget Factory、Draggable)
  • jquery.mousewheel.min.js — 滾輪支援
  • jquery.easing.1.3.js — 緩動效果(可選)
<link href="jquery.mCustomScrollbar.css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
<script src="jquery.mousewheel.min.js"></script>
<script src="jquery.mCustomScrollbar.concat.min.js"></script>

HTML 結構規範

插件要求特定的 DOM 結構,外層容器需設定固定高度或 max-height:

<div id="mcs_container" class="custom-scroll">
  <div class="content">
    <!-- 這裡放置長內容:文字、圖片、表格等 -->
  </div>
</div>

初始化與常用配置

$(function () {
  $('#mcs_container').mCustomScrollbar({
    theme: 'minimal-dark',           // 內建主題:light, dark, minimal, light-3 等
    scrollInertia: 300,              // 滾動動畫時長 (ms)
    mouseWheel: { scrollAmount: 120 }, // 滾輪步長
    scrollButtons: { enable: true }, // 顯示上下按鈕
    keyboard: { enable: true },      // 鍵盤方向鍵控制
    advanced: {
      autoExpandHorizontalScroll: true,
      updateOnContentResize: true    // 內容動態變化時自動更新
    },
    callbacks: {
      onScrollStart: function () { console.log('開始滾動'); },
      onScroll: function () { /* 滾動中 */ },
      onTotalScroll: function () { console.log('到底部'); }
    }
  });
});

進階用法示例

1. 動態載入內容

function loadNewContent(containerId, url) {
  const $container = $('#' + containerId);
  $.get(url, function (html) {
    $container.find('.mCSB_container').append(html);
    $container.mCustomScrollbar('update');
  });
}

2. 程式化控制滾動位置

// 滾動到底部
$('#mcs_container').mCustomScrollbar('scrollTo', 'bottom', { scrollInertia: 500 });

// 滾動到指定元素
$('#mcs_container').mCustomScrollbar('scrollTo', '#target-element');

// 獲取當前滾動位置
const pos = $('#mcs_container').mCustomScrollbar('scrollTo', 'get');

3. 多容器同步滾動

$('.sync-scroll').mCustomScrollbar({
  callbacks: {
    onScroll: function () {
      const pct = this.mcs.topPct;
      $('.sync-scroll').not(this).mCustomScrollbar('scrollTo', pct + '%', { scrollInertia: 0 });
    }
  }
});

常見問題與最佳實踐

  • 容器無高度:必須在 CSS 給容器明確高度或 max-height,否則滾動條不會顯示。
  • 動態內容未更新:內容 AJAX 載入或 DOM 變更後,務必呼叫 .mCustomScrollbar('update')。
  • 行動裝置觸控:插件內建觸控支援,無需額外配置;若需禁用可設 touch: false。
  • 銷毀實例:$('#mcs_container').mCustomScrollbar('destroy') 可完全移除並恢復原生滾動。

結語

mCustomScrollbar 以靈活的配置、完善的事件體系與跨瀏覽器相容性,成為客製化滾動條的首選方案。掌握其核心 API 後,即可輕鬆實現從簡單的內容區塊滾動到複雜的同步滾動、虛擬列表等進階場景。


參考資源:GitHub 官方倉庫 | 官方文檔與示例

copyright © 萬盛學電腦網 all rights reserved