
在 「小程序」 中怎么实现这种横向滚动效果呢。
说起来也简单,直接上代码吧
1 .WXML
-
分类区域使用小程序的scroll-view,绑定bindscroll事件,动态计算scroll-left的距离
-
滚动条区域写用两个view模拟滚动条,滚动条的宽度和滚动距离都根据分类的内容来计算
<!-- 分类区域 -->
<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>
<!-- 滚动条区域 -->
<view class="scroll-bar">
<view class="scroll-bar__bg">
<view class="scroll-bar__slide" style="width: {{barW}}rpx;left:{{percent}}rpx"></view>
</view>
</view>
复制代码
2 .CSS
.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;
}
复制代码
3 .JS
data: {
percent: 0, //滚动条距离左边的距离
barW: 0, //滚动条的宽度
}
/* 计算滚动区域的宽度 */
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
})
},
|