实现小程序tab栏下划线动画效果

最终效果

实现

wxml

<view class='abox'>
    <view wx:for="{{title}}" class='{{currentIndex==index?"tabTrue":""}}'  bindtap='changeTab' data-aa='{{index}}'>
      {{item}}
    
    </view>
    <view class='b' style="left:{{left}}px"></view>
</view>

wxss

.abox{
  display: flex;
  flex-direction: row;
  width: 100%;
  justify-content: space-around;
  position: relative;
  padding-bottom: 20rpx;
}

.tabTrue{
  color: red;
}
.b{
  background: red;
  height: 4rpx;
  width:64rpx;
  position: absolute;
  bottom: 0;
  transition: all .3s linear;
}

js

Page({
  data: {
    title: ["首页","掘金","思否","知乎"],
    currentIndex:"0",
    left:""
  },
  changeTab:function(e){
    //console.log(e)
    this.setData({
      currentIndex: e.currentTarget.dataset.aa
    })
    this.changeline(e)
    
  },
  changeline:function(){
    const query = wx.createSelectorQuery()
    var _this = this
    query.select('.tabTrue').boundingClientRect()
    query.exec(function (res) {
      _this.setData({
        left: res[0].left
      })
      //console.log(res[0].left)
    })
  },
  onLoad: function () {
    
    this.changeline(1)
   
  }
})

上面代码可以实现效果,这里面最重要的就是通过 changeTab方法获取有tabtrue这个class的标签,获取到标签的left值。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理