在 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>
插件要求特定的 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('到底部'); }
}
});
});
function loadNewContent(containerId, url) {
const $container = $('#' + containerId);
$.get(url, function (html) {
$container.find('.mCSB_container').append(html);
$container.mCustomScrollbar('update');
});
}
// 滾動到底部
$('#mcs_container').mCustomScrollbar('scrollTo', 'bottom', { scrollInertia: 500 });
// 滾動到指定元素
$('#mcs_container').mCustomScrollbar('scrollTo', '#target-element');
// 獲取當前滾動位置
const pos = $('#mcs_container').mCustomScrollbar('scrollTo', 'get');
$('.sync-scroll').mCustomScrollbar({
callbacks: {
onScroll: function () {
const pct = this.mcs.topPct;
$('.sync-scroll').not(this).mCustomScrollbar('scrollTo', pct + '%', { scrollInertia: 0 });
}
}
});
max-height,否則滾動條不會顯示。.mCustomScrollbar('update')。touch: false。$('#mcs_container').mCustomScrollbar('destroy') 可完全移除並恢復原生滾動。mCustomScrollbar 以靈活的配置、完善的事件體系與跨瀏覽器相容性,成為客製化滾動條的首選方案。掌握其核心 API 後,即可輕鬆實現從簡單的內容區塊滾動到複雜的同步滾動、虛擬列表等進階場景。
參考資源:GitHub 官方倉庫 | 官方文檔與示例