
在 「小程序」 中怎么實(shí)現(xiàn)這種橫向滾動(dòng)效果呢。
說(shuō)起來(lái)也簡(jiǎn)單,直接上代碼吧
<!-- 分類(lèi)區(qū)域 -->
<view class="scroll-wrap">
<scroll-view scroll-x="true" scroll-with-animation="true" bindscroll="spikeScroll" class="scroll scroll-x" scroll-left="{{scrollLeft}}">
<view class="scroll-item index-nav" wx:for="{{catList}}" wx:key="catId">
<view class="index-nav-item flex-y-fs {{item.selected?'selected':''}}" data-idx="{{index}}" data-catid="{{item.catId}}" bindtap="handleClickCat">
<view class="cat-img-wrap">
<image class="" src="{{item.catPicUrl}}" mode=""></image>
</view>
<text>{{item.catName}}</text>
</view>
</view>
</scroll-view>
</view>
<!-- 滾動(dòng)條區(qū)域 -->
<view class="scroll-bar">
<view class="scroll-bar__bg">
<view class="scroll-bar__slide" style="width: {{barW}}rpx;left:{{percent}}rpx"></view>
</view>
</view>
復(fù)制代碼
.scroll-wrap {
width: 100%;
box-sizing: border-box;
background: #ffffff;
}
.scroll {
height: 100%;
box-sizing: border-box;
}
.scroll-x {
display: flex;
width: 100%;
white-space: nowrap;
overflow-x: auto;
}
.scroll-item {
width: 138rpx;
display: inline-block;
margin-right: 10rpx;
padding: 0 24rpx 27rpx;
font-size: 24rpx;
color: #4e4e4e;
font-family: PingFangSC-Regular, PingFang SC;
}
.scroll-bar {
background: #ffffff;
}
.scroll-bar__bg {
position: relative;
width: 86rpx;
height: 6rpx;
background: #d4d8dd;
border-radius: 5px;
margin: 0 auto;
overflow: hidden;
}
.scroll-bar__slide {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: rgba(233, 89, 14, 1);
border-radius: 5px;
}
復(fù)制代碼
data: {
percent: 0, //滾動(dòng)條距離左邊的距離
barW: 0, //滾動(dòng)條的寬度
}
/* 計(jì)算滾動(dòng)區(qū)域的寬度 */
countCatWidth () {
var query = wx.createSelectorQuery();
//選擇id
var that = this;
query.select('.scroll-item').boundingClientRect(function (rect) {
let sw = (rect.width+5)*that.data.catList.length+5
that.setData({
barW: (86/sw)*wx.getSystemInfoSync().windowWidth
})
}).exec();
},
//bindscroll事件
spikeScroll(e) {
let barW = (86/e.detail.scrollWidth)*wx.getSystemInfoSync().windowWidth
this.setData({
barW: barW,
percent: (86/e.detail.scrollWidth)*e.detail.scrollLeft
})
},