本文主要介绍:利用Vue实现tab导航栏,并且通过flex布局实现左右滑动,计算按钮的位置,当点击第一屏展示的最后一个且还有元素未展示时,自动滑动显示出未显示的元素。
tab导航栏布局:
- <section class="theme-list">
- <div class="fixed-nav" ref="fixednav">
- <div class="fixed-nav-content">
- <p
- v-for="(item, index) in theme"
- :key="index"
- :class="['tab-title', activeId === index && 'select-tab']"
- @click="changeTab(index, $event)"
- >
- {{ item }}
- </p>
- </div>
- </div>
- </section>
- theme: ['CSDN博客', '博客园', '高考加油', '中考加油', '小欢喜', '七十周年'],
- activeId: 0
导航栏样式代码:
- .theme-list {
- margin-top: 12px;
- }
- .fixed-nav {
- overflow-x: scroll;
- -webkit-overflow-scrolling: touch;
- }
- .fixed-nav-content {
- display: flex;
- }
- .tab-title {
- padding: 0 13px;
- margin-right: 12px;
- color: #141414;
- border-radius: 13px;
- font-size: 12px;
- flex-shrink: 0;
- height: 0.52rem;
- line-height: 0.52rem;
- }
此时我们可以实现下面的样式,并且可以左右滑动tab:

需要注意的是,在样式代码中需要添加flex-shrink : 0
,这样才会当tab宽度大于外部容器宽度时不会收缩。
这样,我们基本的tab导航栏已经实现了,现在我们来实现:点击“中考加油”时,整个tab向左滑动,显示出剩下的tab元素。
- changeTab(id, event) {
- // 如果选择的和当前激活的不同
- if (id !== this.activeId) {
- this.activeId = id;
- // 计算当前按钮的位置,看是否需要移动
- const spanLeft = event.clientX; // 当前点击的元素左边距离
- const divBox = document.querySelector(".select-tab").clientWidth / 2; // 点击的元素一半宽度
- const totalWidths = document.body.clientWidth; // 屏幕总宽度
- const widths = totalWidths / 2; // 一半的屏幕宽度
- const spanRight = totalWidths - spanLeft; // 元素的右边距离
- const scrollBox = document.querySelector(".fixed-nav"); // 获取最外层的元素
- const scrollL = scrollBox.scrollLeft; // 滚动条滚动的距离
- // 当元素左边距离 或者 右边距离小于100时进行滑动
- if (spanRight < 100 || spanLeft < 100) {
- scrollBox.scrollLeft = scrollL + (spanLeft - widths) + divBox;
- }
- }
- }
通过这个方法可以实现tab的自动滚动了,但是此时还有一个问题是:在滑动的时候会显示出滚动条,显然是不太美观的。
- /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
- ::-webkit-scrollbar {
- width: 0.01rem;
- opacity: 0;
- display: none;
- }
- /*定义滚动条轨道 内阴影+圆角*/
- ::-webkit-scrollbar-track {
- background-color: #fff;
- opacity: 0;
- }
- /*定义滑块 内阴影+圆角*/
- ::-webkit-scrollbar-thumb {
- width: 0.01rem;
- border-radius: 0.01rem;
- opacity: 0;
- }
这样,一个导航条就实现了,可以在结合公司的业务修改一下导航条的样式就可以啦!
到此这篇关于Vue实现tab导航栏,支持左右滑动的文章就介绍到这了,更多相关Vue左右滑动导航栏内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!