HTML的代码
<view>
<scroll-view scroll-x scroll-left="{{scrollLeft}}" scroll-with-animation class="scroll-view">
<view class="class-item {{item.select == true ? 'fujia':'' }}" wx:for="{{topArray}}" wx:key="id" @tap="switchClass" data-id="{{item.id}}">
<text class="name">{{item.title}}</text>
</view>
</scroll-view>
</view>
逻辑的
data = {
topArray: [
{ title: '游览点哈', id: 2},
{ title: '卫生间哈', id: 13 },
{ title: '视频监控', id: 11 },
{ title: '智能广播', id: 12 },
{ title: '出入口哈', id: 14 },
{ title: '观光车哈', id: 15 },
{ title: '智能广播', id: 16 },
{ title: '出入口哈', id: 17 },
{ title: '观光哈哈', id: 18 },
{ title: '智能广播', id: 19 },
{ title: '出入口哈', id: 20 },
{ title: '观光车哈', id: 21 },
{ title: '出入口哈', id: 22 },
{ title: '观光车哈', id: 23 },
{ title: '智能广播', id: 24 },
{ title: '出入口哈', id: 25 },
{ title: '观光哈哈', id: 26 },
{ title: '智能广播', id: 27 },
{ title: '出入口哈', id: 28 },
{ title: '观光车哈', id: 29 },
],
scrollViewWidth:'',
scrollLeft:'',
};
methods = {
switchClass(e){
let offsetLeft = e.currentTarget.offsetLeft
let idkl = e.currentTarget.dataset.id
this.scrollLeft = offsetLeft - this.scrollViewWidth / 2 + 40
console.log("this.scrollLeft>>>>" + JSON.stringify(this.scrollLeft))
this.topArray.map(item=>{
if(idkl == item.id){
item.select = true
}else{
item.select = false
}
return item
})
this.$apply();
}
};
onReady(){
wx.createSelectorQuery().select('.scroll-view').boundingClientRect((rect)=>{
this.scrollViewWidth = Math.round(rect.width)
console.log("scrollViewWidth>>>>" + JSON.stringify(this.scrollViewWidth))
}).exec()
}
onLoad (options) {
let self = this;
self.topArray.map(item=>{
item.select = false
return item
})
self.topArray[0].select = true;
self.$apply();
}
CSS的代码
.scroll-view{
display: inline-block;
height: 80rpx;
white-space: nowrap;
}
.class-item{
display: inline-block;
width:150rpx;
text-align: center;
font-size: 26rpx;
color: #333;
height: 80rpx;
line-height: 80rpx;
position: relative;
}
.fujia{
color: red;
font-size: 30rpx;
font-weight: bold;
}
.fujia::after{
content: '';
position: absolute;
left: 55rpx;
bottom: 0;
right: 0;
width: 40rpx;
height: 4rpx;
background-color: red;
}