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

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

相关推荐
程序员爱钓鱼2 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
PineappleCoder2 小时前
工程化必备!SVG 雪碧图的最佳实践:ID 引用 + 缓存友好,无需手动算坐标
前端·性能优化
JIngJaneIL2 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码2 小时前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_3 小时前
列表渲染(v-for)
前端·javascript·vue.js
JustHappy3 小时前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github
Loo国昌3 小时前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
sg_knight3 小时前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
LYFlied3 小时前
【每日算法】LeetCode 17. 电话号码的字母组合
前端·算法·leetcode·面试·职场和发展