『更智能的滚动条』一劳永逸,无副作用

344 阅读1分钟

书接上回,『CSS滚动条 完整兼容』一劳永逸,无副作用

上篇文章说到全局样式文件中写

html { 
    box-sizing: border-box;
    scrollbar-width: thin;
}
*,
*:before,
*:after { 
    box-sizing: inherit; 
    scrollbar-width: inherit; 
} 
*::-webkit-scrollbar {
    width: 10px;
    height: 10px;
} 
*::-webkit-scrollbar-thumb { 
    background: hsl(214, 13%, 75%);
    border-radius: 4px;
}

这里有个问题

Mac OS 系统本身会自动隐藏的滚动条,因为设置了 -webkit-scrollbar 导致自动隐藏失效,这对 mac 系统其实是一个变坏的体验。

可以有统一的方案?有,有的框架实现了自己画滚动条。

这里,我们采用简单的判断 windows 环境,在 windows 环境再全局替换滚动条

new

依然全局加载样式

// 添加成立条件
.windows {
    *,
    *:before,
    *:after {
    // 新版 FireFox 已经也会自动隐藏了,不用刻意设置
        scrollbar-width: thin;
        scrollbar-color: hsl(0deg 0% 50%) transparent;
    }

    *::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }
    *::-webkit-scrollbar-thumb {
        background: hsla(0, 0%, 0%, 0.5);
        border-radius: 99px;
    }
}

新增 js 逻辑

// navigator.userAgent is unreliable,但只是设置滚动条也无妨
if (/windows|win32/i.test(navigator.userAgent)) {
    // 设置 html 标签保证影响全局
    // classList.add 有效防止重复添加
    document.documentElement.classList.add('windows')
}

备忘

判断 mac|iphone 环境:

/macintosh|mac os x/i.test(navigator.userAgent);