萬盛學電腦網

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

JavaScript 實現捲動條隨滑鼠移動變色特效(IE 專屬 scrollbar 樣式)

效果描述

滑鼠移至頁面右側捲動條區域時,捲動條顏色變為深藍系;移開則恢復預設「neo」主題。僅支援 IE(使用非標準 scrollbar-* CSS 屬性)。

原始代碼解析

function scrollBar(line, face, theme) {
    if (!line || !face) {
        line = face = null;
        switch(theme) {
            case 'blue':   line='#78AAFF'; face='#EBF5FF'; break;
            case 'orange': line='#FBBB37'; face='#FFF9DF'; break;
            case 'red':    line='#FF7979'; face='#FFE3DD'; break;
            case 'green':  line='#00C600'; face='#D1EED0'; break;
            case 'neo':    line='#BC7E41'; face='#EFE0D1'; break;
        }
    }
    // 套用到 body.style (IE 專屬)
    with(document.body.style) {
        scrollbarDarkShadowColor = line;
        scrollbar3dLightColor    = line;
        scrollbarArrowColor      = 'black';
        scrollbarBaseColor       = face;
        scrollbarFaceColor       = face;
        scrollbarHighlightColor  = face;
        scrollbarShadowColor     = face;
        scrollbarTrackColor      = '#F3F3F3';
    }
}

function colorBar() {
    var w = document.body.clientWidth;
    var x = event.clientX;
    if (x > w) scrollBar('#000080', '#BFDFFF'); // 滑鼠在捲動條區 (x > 可視寬)
    else scrollBar(null, null, 'neo');
}

if (document.all) { // IE 判斷
    scrollBar(null, null, 'neo');
    document.onmousemove = colorBar;
}

技術背景:IE 捲動條樣式屬性

現代標準:CSS Scrollbar Styling (Chrome/Edge/Firefox 64+)

/* 整體捲動條 */
::-webkit-scrollbar { width: 12px; height: 12px; }
::-webkit-scrollbar-track { background: #f1f1f1; }
::-webkit-scrollbar-thumb { background: #888; border-radius: 6px; }
::-webkit-scrollbar-thumb:hover { background: #555; }
::-webkit-scrollbar-corner { background: transparent; }

/* Firefox */
* { scrollbar-width: thin; scrollbar-color: #888 #f1f1f1; }

動態切換主題 (現代跨瀏覽器)

const themes = {
    neo: { thumb: '#BC7E41', track: '#EFE0D1' },
    blue: { thumb: '#78AAFF', track: '#EBF5FF' },
    dark: { thumb: '#555', track: '#222' }
};

function setScrollbarTheme(name) {
    const t = themes[name] || themes.neo;
    // CSS 變數法 (需 CSS 定義變數)
    document.documentElement.style.setProperty('--sb-thumb', t.thumb);
    document.documentElement.style.setProperty('--sb-track', t.track);
    // Firefox 需直接設定 (無法用變數)
    document.documentElement.style.scrollbarColor = `${t.thumb} ${t.track}`;
}

// 滑鼠進入右側區域切換 (示意)
document.addEventListener('mousemove', e => {
    if (e.clientX > window.innerWidth - 20) setScrollbarTheme('blue');
    else setScrollbarTheme('neo');
});

結語

IE 專屬 scrollbar-* 屬性已被標準化的 ::-webkit-scrollbar 與 scrollbar-color/width 取代。現代專案應使用標準 CSS,配合 CSS 變數實現動態主題切換。若必須支援舊 IE,可透過條件註釋載入兼容腳本,但建議優雅降級(忽略捲動條樣式)。

copyright © 萬盛學電腦網 all rights reserved
屬性控制部位
scrollbarFaceColor滑塊、箭頭按鈕主色
scrollbarTrackColor軌道背景色
scrollbarArrowColor箭頭顏色
scrollbarBaseColor基礎色(影響 3D 邊框)
scrollbar3dLightColor / scrollbarDarkShadowColor3D 邊框高光/陰影
scrollbarHighlightColor / scrollbarShadowColor次要高光/陰影