scroll-marker实现tab效果

前言

tab 组件是我们经常使用到的,以前实现方式大多需要借助js去动态判断当前展示的是哪个tab项,再动态渲染对应的项,若需要实现过度动画还需要比较复杂的控制。最近发现一个很好用的css属性scroll-marker可以直接实现tab效果并且还有切换动画。

效果展示

实现代码

html 部分

html部分仅需要填入内容即可,使用--tab-title变量来传递tab的标题

html 复制代码
<div class="tab">
  <div class="item" style="--tab-title: 'tab1';">tab content 1</div>

  <div class="item" style="--tab-title: 'tab2';">
    <h3>tab content 2</h3>
    <p>1212312</p>
  </div>

  <div class="item" style="--tab-title: 'tab3';">tab content 3</div>

  <div class="item" style="--tab-title: 'tab4';">tab content 4</div>
</div>

css 部分

::scroll-marker-group:伪元素,是子元素的::scroll-marker的父节点,有before和after两个值,表示该伪元素是在tab的前面还是后面

::scroll-marker:伪元素,与每一项直接关联,点击后tab会滚动到对应项的位置

:target-current:伪类,表示当前滚动的位置

css 复制代码
.tab {
  display: flex;
  flex-direction: row;
  position: relative;

  overflow: auto;
  scrollbar-width: none;
  overscroll-behavior-x: contain;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth; /** 平滑滚动 */
  scroll-marker-group: before;
}

.tab::scroll-marker-group {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  box-sizing: border-box;
  overflow-x: auto;
  scrollbar-width: none;
  height: 36px;
  line-height: 36px;
  width: 100%;
  border-bottom: 1px solid #ccc;
}

.tab .item {
  scroll-snap-align: start;
  min-width: 100%;
  min-height: 100%;
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.tab .item::scroll-marker {
  display: inline-block;
  content: var(--tab-title);
  text-decoration: none;
  color: #333;
  padding: 0 8px;
  height: 34px;
  line-height: 34px;
  border-bottom: 2px solid transparent;
}

.tab .item::scroll-marker:hover {
  color: #409eff;
}

.tab .item::scroll-marker:target-current {
  color: #409eff;
  border-color: #409eff;
}

总结

利用scroll-marker还可以实现更多有趣的效果,例如侧导航栏、轮播图等。但是目前浏览器对该伪类的支持还不是很好,可以在不兼容老版本浏览器的情况下使用。

最后推荐一下低代码平台我的应用,可以直接去下载后私有化部署且完全免费。开源不易,望多多支持,也可通过平台提出宝贵意见,感谢!

相关推荐
研☆香10 分钟前
jQuery特殊属性操作方法
前端·javascript·jquery
ShiJiuD66688899914 分钟前
外卖项目总结下 (前端板块)
前端
liming49526 分钟前
Maven中央库迁移
服务器·前端·maven
超哥--7 小时前
B站视频内容智能分析系统(九):React 前端与管理面板
前端·react.js·前端框架
Cutecat_10 小时前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
qq_4221525710 小时前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
kyriewen11 小时前
手写 Promise.all、race、any:不到 30 行代码,解决并发异步的所有姿势
前端·javascript·面试
brucelee18611 小时前
OpenClaw 浏览器控制(Chrome MCP)完整教程
前端·chrome
ct97812 小时前
React 状态管理方案深度对比
开发语言·前端·react
胡志辉的博客12 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·chrome·chromium·event loop