DIV CSS 佈局教程網

jQuery 自訂滾動條外掛的參數與用法
編輯:JavaScript綜合知識     

malihu 的 Custom Scrollbar 是早期相當受歡迎的滾動條美化外掛,靠 jQuery UI 的 easing 做出不同手感。這份範例一次展示五種組態。

依賴與載入

<link href="jquery.mCustomScrollbar.css" rel="stylesheet" type="text/css" />
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
<script src="jquery.easing.1.3.js"></script>
<script src="jquery.mousewheel.min.js"></script>
<script src="jquery.mCustomScrollbar.js"></script>

結構上每個滾動區都是「customScrollBox > container > content」,另外需要一個 dragger_container 放拖曳把手;水平滾動時還要多包一層名為 horWrapper 的 div,少了它水平滾動不會作用。

八個參數

参数說明:
1) scroll type   捲動方向:"vertical" 或 "horizontal"
2) easing amount 緩動強度,0 表示不做緩動
3) easing type   緩動函式名稱,如 "easeOutCirc"
4) extra space   垂直捲動時底部的額外留白(最小 1)
5) size adjust   把手尺寸:"auto" 或 "fixed"
6) mousewheel    是否支援滑鼠滾輪:"yes" / "no"
7) buttons       是否顯示上下(左右)按鈕:"yes" / "no"
8) btn speed     按鈕捲動速度 1-20,1 最慢

初始化

$(window).load(function () {
  mCustomScrollbars();
});

function mCustomScrollbars() {
  $("#mcs_container").mCustomScrollbar("vertical",   400, "easeOutCirc", 1.05, "auto",   "yes", "yes", 10);
  $("#mcs2_container").mCustomScrollbar("vertical",  0,   "easeOutCirc", 1.05, "auto",   "yes", "no",  0);
  $("#mcs3_container").mCustomScrollbar("vertical",  900, "easeOutCirc", 1.05, "auto",   "no",  "no",  0);
  $("#mcs4_container").mCustomScrollbar("vertical",  200, "easeOutCirc", 1.25, "fixed",  "yes", "no",  0);
  $("#mcs5_container").mCustomScrollbar("horizontal",500, "easeOutCirc", 1,    "fixed",  "yes", "yes", 20);
}

/* 動態載入新內容後要重新初始化 */
function LoadNewContent(id, file) {
  $("#" + id + " .customScrollBox .content").load(file, function () {
    mCustomScrollbars();
  });
}

把初始化包成具名函式是這份範例最實用的地方:因為用 load() 換掉內容後,把手的高度必須重算,若不重跑一次初始化,捲動比例就會失準。

兩個細節

範例覆寫了 $.fx.prototype.cur,目的是繞過 jquery.animate 對 -10000 這種極端值的處理限制。這是針對舊版 jQuery 的相容补丁,在新版上未必需要,甚至可能造成非預期行為,採用前請先確認你的 jQuery 版本。

另外它提供了 <noscript> 的退路:停用 JS 時讓 .customScrollBox 改回 overflow: auto 並隱藏把手,內容仍然讀得到。這種「JS 增強、無 JS 仍可用」的設計原則值得保留,用 CSS 動畫或原生 scroll 樣式時也一樣適用。

今天怎麼選

這個外掛已多年未更新,依賴的 jQuery 1.4 與 jQuery UI 1.8 都相当舊。現代專案若要美化滾動條,::-webkit-scrollbar 這類 CSS 偽元素加上 scrollbar-width/scrollbar-color 就能覆蓋多數瀏覽器,不必背 1MB 的 JS;需要自訂把手的特殊交互時,再考慮仍在維護的替代方案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved