wxmlxss
<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>
wxssflex
.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; }
jsthis
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) } })
wxmlspa
<view class='abox'> <view wx:for="{{title}}" class='tab {{currentIndex==index?"tabTrue":""}}' bindtap='changeTab' data-aa='{{index}}'> {{item}} </view> <view class='b' style='left:{{left}}px;transform: translateX({{width}}rpx);'></view> </view>
wxsscode
.abox{ display: flex; flex-direction: row; width: 100%; /* justify-content: space-around; */ position: relative; padding-bottom: 20rpx; } .tabTrue{ color: red; } .tab{ width: 50%; text-align: center; } .b{ background: red; height: 4rpx; width:64rpx; position: absolute; bottom: 0; left: 50%; transition: all .3s linear; }
jsorm
Page({ data: { title: ["首頁", "掘金", ], currentIndex:"0", left:"0", width:"", }, 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.setData({ left:this.data.left, width: this.data.width = (750 / this.data.title.length - 64)/2 //設置偏移 64是橫線的寬度 }) } })
上面兩個均可以實現效果,這裏面最重要的就是經過 changeTab方法獲取有tabtrue這個class的標籤,獲取到標籤的left值。xml