You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让注入CSS覆盖原有样式,一次性隐藏所有可滚动元素的滚动条

隐藏网页所有滚动条并保持可滚动的问题

我希望隐藏网页内的所有滚动条,同时让每个可滚动元素始终保持可滚动能力。

我正在开发一个注入式JavaScript文件,会在访问的每个网页中添加一个<style>元素,但部分页面存在自定义样式的滚动条,导致我的样式无法全部生效。

我的注入脚本如下:

const styleTag = document.createElement("style")

styleTag.textContent = `

    ::-webkit-scrollbar {
        appearance: none !important;
        width: 0;
        height: 0;
    }
`

document.head.appendChild(styleTag)

用户@Yogi指出了问题根源:

你的CSS在默认滚动条上运行正常,但对页面已自定义样式的滚动条无效。例如Electron页面会在媒体查询中应用.thin-scrollbar::-webkit-scrollbar样式,因此即使你使用!important,你的CSS仍会被忽略。

最小可复现示例

CSS代码

.container {
  display: flex;
  gap: 1rem;
}

.box {
  box-sizing: border-box;
  padding: 0.5rem;
  overflow: scroll;
  height: 20rem;
  max-height: 100%;
  border: thin solid black;
}

.spacer {
  height: 50rem;
  width: 50rem;
}

@media(pointer:fine) {
  .thin-scrollbar {
    scrollbar-width: thin;
  }
  .thin-scrollbar::-webkit-scrollbar:horizontal {
    /* placeholder */
  }
  .thin-scrollbar::-webkit-scrollbar:vertical {
    /* placeholder */
  }
}

::-webkit-scrollbar {
  appearance: none !important;
  width: 0;
  height: 0;
}

HTML代码

<div class="container">
  <div class="box">
    OK - 滚动条已隐藏<br> 
    这个盒子使用默认滚动条
    <div class="spacer"></div>
    底部
  </div>
  <div class="box thin-scrollbar">
    FAIL - 滚动条可见<br> 
    这个盒子使用自定义样式滚动条
    <div class="spacer"></div>
    底部
  </div>
</div>

现在需要解决的问题是:如何让我注入的CSS成为文档中优先级最高的样式,从而覆盖页面中所有已自定义样式的滚动条?


内容的提问来源于stack exchange,提问作者Joele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 10:37:25