美文网首页
tab底部条下划线滑动实现

tab底部条下划线滑动实现

作者: bug喵 | 来源:发表于2019-07-29 12:17 被阅读0次
本文代码为wepy的微信小程序代码,各位可自行转化为H5及其他框架代码
1.效果演示
tab下划线滑动.gif
2.代码

//css代码:

.tab_container {
  display: flex;
  align-items: center;
  position: relative;
}
.tab_item {
  width: 33%;
  text-align: center;
  font-size: 30rpx;
  height: 60rpx;
}
.tab_select_bar {
  display: flex;
  justify-content: center;
  width: 33%;
  position: absolute;
  left: 0;
  bottom: 1rpx;
  transform-origin: 0 0;
  transform: translate3d(0rpx, 0rpx, 0rpx);
  transition-property: all;
  transition-timing-function: cubic-bezier (0.645, 0.045, 0.355, 1);
  transition-duration: 0.1s;
  .bar_line {
    height: 2rpx;
    background-color: #1890ff;
    width: 40%;
  }
}

//wxml代码

<template>
 <view>
   <view class="tab_container">
    <repeat for="{{tabList}}" key="index" index="index" item="item" >
      <view class="tab_item" @tap="selectTab" data-tab="{{item}}" data-index="{{index}}">
        {{item.name}}
      </view>
    </repeat>
    <view class="tab_select_bar"
      style="transform:translate3d({{tabTransNum}}rpx, 0rpx, 0rpx)">
      <view class="bar_line"/>
    </view>
   </view>
 </view>
</template>

//js 代码

let tabList = [
  { key: 1, name: "测试1" },
  { key: 2, name: "测试2" },
  { key: 3, name: "测试3" }
];

let tabTransBaseNum = Math.floor(750 / 3);

export default class Test extends wepy.page {
  components = {};

  config = {
    navigationBarTitleText: "tab底部线条滑动"
  };

  data = {
    tabList,
    tabTransNum: 0
  };

  computed = {};

  async onLoad() {}

  async onShow() {}

  selectTab(e) {
    const tab = e.currentTarget.dataset.tab;
    const index = e.currentTarget.dataset.index;
    this.tabTransNum = tabTransBaseNum * index;
  }
}
3.稍稍分析下

(1)层级位置:平常不需要滑动的下滑线我是习惯直接写成tab_item的border的,但是要滑动的话就只能定位到tab_container这一层了。
(2)js改变left的值:我们用left的变动来做滑动,所以点击选择一个tab时让left的值变动到选择的tab下面,这里我定义了一个tabTransBaseNum基础值,然后乘以点击的index来实现。
(3)css添加过渡动画:js改变了left的值后,只要加个过渡效果就可以实现动画了。过渡的曲线函数由于自己把握不好感觉,所以我扒了ant Design的过渡函数transition-timing-function: cubic-bezier (0.645, 0.045, 0.355, 1)。

4.后续可优化的地方

(1)选择得到的当前的tab的key这里我并没有写,小伙伴可自行实现并将其与data里的tabTransNum这个变量合为一体。
(2)由于我的tab只用到了一处,且数量固定为3个,所以没有封装组建,width也写死为33%。有需要的小伙伴可以封装组建并根据传入的tabList自动计算width的值。

相关文章

网友评论

      本文标题:tab底部条下划线滑动实现

      本文链接:https://www.haomeiwen.com/subject/cnghrctx.html