萬盛學電腦網

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

jQuery 實作自訂捲軸:同步內容捲動與捲軸拖曳、動態計算捲軸長度位置

功能概述

自訂捲軸元件,以 DIV 模擬原生捲動條,解決原生捲軸樣式難以客製化、跨瀏覽器不一致的問題。核心邏輯:

  • 計算內容高度與可視區高度比例,決定捲軸高度
  • 內容捲動時 (scroll 事件) 同步更新捲軸位置
  • 拖曳捲軸時 (mousedown/mousemove/mouseup) 反向控制內容 scrollTop
  • 支援視窗 resize 重新計算

核心 JavaScript 邏輯 (ES5 寫法)

var scrMinHeight = 1;          // 捲軸最小高度 (px)
var scrMaxHeight = 0;          // 捲軸最大高度 (可視區高度)
var scrDefaultTop = 80;        // 捲軸預設起始 top 位置
var scrHeight = 0;             // 計算後的捲軸高度

// 初始化捲軸尺寸
function InitScroll() {
    scrMaxHeight = $('#mainScrollContent').height();           // 可視區高度
    var scrollH = document.getElementById('mainScrollContent').scrollHeight; // 內容總高度
    scrHeight = parseInt((scrMaxHeight / scrollH) * scrMaxHeight); // 比例換算
    if (scrHeight <= scrMinHeight) scrHeight = scrMinHeight;
    if (scrHeight >= scrMaxHeight) {
        $('#scrollContent').hide(); // 內容未超出,隱藏捲軸
    } else {
        $('#scrollContent').show();
        $('#scrollContent .tiao_mid').css('height', (scrHeight - 19) + 'px'); // 扣除上下箭頭高度
    }
}

// 內容捲動 → 更新捲軸位置
function ChangeScroll() {
    var scrollTop = $('#mainScrollContent').scrollTop();
    var newTop = (scrollTop * scrMaxHeight) / document.getElementById('mainScrollContent').scrollHeight + scrDefaultTop;
    $('#scrollContent').css('top', newTop + 'px');
}

// 拖曳捲軸 → 更新內容捲動
function ChangeScrollContent() {
    var scrTop = parseInt($('#scrollContent').css('top').replace('px', ''));
    var st = ((scrTop - scrDefaultTop) * document.getElementById('mainScrollContent').scrollHeight) / scrMaxHeight;
    $('#mainScrollContent').scrollTop(st);
}

// 事件綁定
$(document).ready(function() {
    // 尺寸初始化
    $('.bod').height($(document).height() - 80);
    $('#mainScrollContent').height($(document).height() - 125);
    scrMaxHeight = $(document).height() - 125;
    $('#scrollBody, #scrollBodyBack').height(scrMaxHeight);
    InitScroll();

    // 內容捲動事件
    $('#mainScrollContent').scroll(ChangeScroll);

    // 捲軸拖曳事件
    var dragStartY = 0;
    $('#scrollContent').mousedown(function(e) {
        var top = parseInt($(this).css('top').replace('px', ''));
        dragStartY = e.clientY - top;
        $(this).mousemove(function(e) {
            var y = e.clientY - dragStartY;
            // 限制邊界
            if (y < scrDefaultTop) y = scrDefaultTop;
            else if (y > scrDefaultTop + scrMaxHeight - scrHeight) y = scrDefaultTop + scrMaxHeight - scrHeight;
            $(this).css('top', y + 'px');
            ChangeScrollContent();
        });
    }).mouseup(function() {
        $(this).unbind('mousemove');
    }).mouseout(function() {
        $(this).unbind('mousemove');
    });

    // 視窗 resize 重算
    $(window).resize(function() {
        $('.bod').height($(document).height() - 80);
        $('#mainScrollContent').height($(document).height() - 125);
        scrMaxHeight = $(document).height() - 125;
        $('#scrollBody, #scrollBodyBack').height(scrMaxHeight);
        InitScroll();
    });
});

HTML 結構

<!-- 內容區 -->
<div class="jtc_neir" id="mainScrollContent" style="height: 100px; overflow-y: scroll;">
    長內容...
</div>

<!-- 自訂捲軸軌道 -->
<div class="jtc_tiao" id="scrollBodyBack"></div>  <!-- 背景軌道 -->
<div class="jtc_tiao" id="scrollBody"></div>       <!-- 前景軌道 (可選) -->

<!-- 捲軸滑塊 -->
<div class="jtc_tiao" id="scrollContent">
    <div class="tiao_up"></div>      <!-- 頂部箭頭 -->
    <div class="tiao_mid"></div>    <!-- 中間可變高度軸 -->
    <div class="tiao_bottom"></div> <!-- 底部箭頭 -->
</div>

CSS 樣式重點

.jtc_neir {
    overflow-y: scroll; overflow-x: hidden;
    /* 可選:隱藏原生捲軸 (WebKit) */
    /* &::-webkit-scrollbar { display: none; } */
}
.jtc_tiao { width: 8px; position: absolute; top: 80px; right: 20px; z-index: 10; }
.tiao_up    { width: 8px; height: 10px; background: url(../images/scrollbar-3.jpg) left top no-repeat; }
.tiao_mid   { width: 8px; background: url(../images/scrollbar-3.jpg) -39px center repeat-y; }
.tiao_bottom{ width: 8px; height: 10px; background: url(../images/scrollbar-3.jpg) -13px bottom no-repeat; }

現代化替代方案

  • CSS 原生捲軸美化:::-webkit-scrollbar 系列偽元素 (Chrome/Edge/Safari)、scrollbar-width/color (Firefox 64+)、scrollbar-color (標準草案)。零 JS、效能最佳。
  • 成熟庫:SimpleBar、OverlayScrollbars、Perfect Scrollbar (已停止維護但仍可用)、react-scrollbar (React)。
  • CSS overflow: overlay:實驗性功能,捲軸浮動於內容上方。

總結

自訂捲軸核心在於「雙向同步」:內容捲動更新 UI、UI 拖曳控制內容。理解比例換算公式 scrollTop / scrollHeight = thumbTop / trackHeight 即可舉一反三。現代專案優先考慮 CSS 原生美化或成熟庫,僅在極度客製化需求下自行實作。

copyright © 萬盛學電腦網 all rights reserved