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

求助:为overflow:auto元素实现Yarn网站同款滚动条出现动画

实现Yarn风格的滚动条「跳跃式」动画效果

我注意到Yarn网站更新后,设置overflow: auto的HTML元素在滚动条出现时会呈现出「跳跃式」的平滑动画效果。现在需要给Web应用中配置了overflow: auto的.sidebar-view元素添加同款效果。

现有代码

HTML

<div class="sidebar-view">
  content of the div that can cause an overflow...
</div>

CSS

.sidebar-view {
  sidebar style....
  overflow-y: auto;
}
.sidebar-view::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.sidebar-view::-webkit-scrollbar-thumb {
  background-color: #666;
  border-radius: 10px;
}

.sidebar-view::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

实现方案

Yarn的这个效果核心是通过CSS过渡动画,配合滚动条显示/隐藏时的元素内边距调整,实现平滑的「跳跃」感。以下是修改后的完整CSS:

.sidebar-view {
  /* 保留原有侧边栏样式 */
  sidebar style....
  overflow-y: auto;
  /* 添加内边距过渡动画 */
  transition: padding-right 0.2s ease;
  /* Firefox默认隐藏滚动条 */
  scrollbar-width: 0;
}

/* WebKit内核浏览器默认隐藏滚动条 */
.sidebar-view::-webkit-scrollbar {
  width: 0;
  height: 0;
  /* 滚动条宽度过渡动画 */
  transition: width 0.2s ease, height 0.2s ease;
}

/* 触发条件:hover、焦点状态、滚动条滑块激活 */
.sidebar-view:hover::-webkit-scrollbar,
.sidebar-view:focus-within::-webkit-scrollbar,
.sidebar-view::-webkit-scrollbar-thumb:active {
  width: 8px;
  height: 8px;
}

/* 调整内边距,保证内容区域宽度不变 */
.sidebar-view:hover,
.sidebar-view:focus-within {
  /* 替换成你实际的右侧内边距值,比如原有padding-right是16px,就写16px - 8px = 8px */
  padding-right: calc(16px - 8px);
}

/* 保留滚动条滑块样式并添加过渡 */
.sidebar-view::-webkit-scrollbar-thumb {
  background-color: #666;
  border-radius: 10px;
  transition: background-color 0.2s ease;
}

.sidebar-view::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

/* Firefox hover时显示细滚动条 */
.sidebar-view:hover {
  scrollbar-width: thin;
}

关键细节

  • 通过transition实现滚动条宽度和内边距的平滑过渡,模拟「跳跃」动画
  • 同时监听:hover和:focus-within,确保键盘导航时也能触发效果
  • 计算padding-right时,要保证元素内容区域宽度在滚动条显示前后一致,避免内容移位
  • 兼容WebKit(Chrome、Safari)和Firefox浏览器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:52:51