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

如何为::-webkit-scrollbar-thumb伪元素添加hover过渡动画?

解决WebKit滚动条滑块悬停过渡不生效问题

问题背景

鼠标悬停在div垂直滚动条的滑块(::-webkit-scrollbar-thumb)上时,颜色在紫色和粉色间突变,过渡动画未生效,但文本元素的同款过渡效果正常,尝试过transition all也无效,需要实现平滑过渡。

解决方案

问题核心在于过渡属性的定义位置,WebKit对滚动条伪元素的过渡逻辑有特殊要求,调整如下:

修改后的完整代码

p {
  font-size: 20px;
  color: #333;
  -webkit-transition: color 1s ease;
  font-weight: bold;
}

p:hover {
  color: blue;
}

.content {
  width: 200px;
  max-height: 100px;
  border: 1px solid red;
  float: left;
  overflow-y: scroll;
}

.content::-webkit-scrollbar {
  width: 10px;
  background-color: rgb(109, 103, 109);
  border-radius: 30px;
}

.content::-webkit-scrollbar-thumb {
  background-color: rgb(90, 3, 112);
  border-radius: 30px;
  border: 1px solid black;
  /* 仅在基础样式中定义过渡规则 */
  -webkit-transition: background-color 1.2s ease;
}

.content::-webkit-scrollbar-thumb:hover {
  background-color: rgb(253, 182, 194);
}
<div class="content">
  <p class="text-content">
    Text<br> Text
    <br> Text
    <br> Text
    <br> Text
    <br> Text
    <br> Text
    <br> Text
    <br> Text
    <br> Text
    <br> Text
    <br>
  </p>
</div>

关键说明

  1. 过渡属性仅定义在基础样式:WebKit内核浏览器要求滚动条伪元素的过渡规则必须写在伪元素的默认样式中,而非hover触发的样式里。如果在hover状态才添加过渡属性,浏览器会在触发hover时才初始化过渡逻辑,导致无法实现平滑过渡。
  2. 修正无效颜色值:原代码中dark-grey不是合法CSS颜色值,替换为标准深灰色#333,确保文本样式正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:35:30