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

如何在Bootstrap 5中禁用custom-range且不改变样式?

解决方法

要让滑块禁用但保持启用时的样式,你得覆盖Bootstrap对custom-range:disabled设置的默认样式——默认情况下它会给禁用的滑块加透明度、灰度滤镜,还改了轨道和拖动按钮的颜色,导致外观变灰变浅。

直接用下面的代码就能实现:

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" />

  <style>
    /* 去掉禁用状态的透明度和灰度滤镜 */
    input.custom-range:disabled {
      opacity: 1;
      filter: none;
    }

    /* 把禁用滑块的轨道样式还原成启用状态的颜色 */
    input.custom-range:disabled::-webkit-slider-runnable-track {
      background-color: #dee2e6;
    }

    input.custom-range:disabled::-moz-range-track {
      background-color: #dee2e6;
    }

    input.custom-range:disabled::-ms-track {
      background-color: #dee2e6;
    }

    /* 把禁用滑块的拖动按钮还原成启用状态的蓝色 */
    input.custom-range:disabled::-webkit-slider-thumb {
      background-color: #0d6efd;
    }

    input.custom-range:disabled::-moz-range-thumb {
      background-color: #0d6efd;
    }

    input.custom-range:disabled::-ms-thumb {
      background-color: #0d6efd;
    }
  </style>
</head>

<body>
  <div class="container mb-4 col-sm-5">
    <!-- 对比用的启用状态滑块 -->
    <input type="range" class="custom-range" min="0" max="10" value="10" style="width: 100%">
    <!-- 禁用但样式不变的滑块 -->
    <input type="range" class="custom-range" min="0" max="10" value="10" style="width: 100%" disabled>
  </div>
</body>

</html>

为啥之前的代码没用?

你之前只改了background和color,但Bootstrap对禁用滑块的样式修改根本不在这些属性上,它是通过opacity、filter以及针对不同浏览器的滑块伪元素(比如::-webkit-slider-runnable-track)来调整样式的,所以只改背景色完全起不到作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:10:13