原理:基于scroll-view实现自定义滚动条效果,达到实现需求的目的。
wxml
<scroll-view bindscroll="scroll" enhanced bounces="{{false}}" scroll-x style="width: 100%; white-space: nowrap" data-window-width="{{systemInfo.windowWidth}}">
<view wx:for="{{10}}" style="width: 100rpx; height: 60rpx; display: inline-block;">{{item}}</view>
</scroll-view>
<view class="scroll-bar">
<view class="scroll-bar__bg">
<view class="scroll-bar__slide" style="left:{{scrollBarLeft}}px"></view>
</view>
</view>
wxss
.scroll-bar {
padding: 30rpx 0;
}
.scroll-bar__bg {
position: relative;
width: 100%;
height: 2rpx;
background: #edf0f0;
}
.scroll-bar__slide {
position: absolute;
top: 0;
left: 0;
width: 100rpx;
height: 100%;
background: #031c24;
/* transition: left 0.3s; */
}
js
const app = getApp()
Page({
data: {
systemInfo:null,
scrollBarLeft: 0
},
onLoad() {
const systemInfo = wx.getSystemInfoSync();
this.setData({
systemInfo
})
},
/**
* @method scroll 横向滚动
*/
scroll(e) {
const {systemInfo} = this.data
const { scrollLeft, scrollWidth } = e.detail;
const { windowWidth } = systemInfo;
// 最大滚动宽度,如果有内外边距记得要减去
const maxScrollWidth = scrollWidth - windowWidth;
// 滚动条的宽度, 如果有内外边距记得要减去
const scrollBarWidth = windowWidth - 50;
const scrollRatio = scrollLeft / maxScrollWidth;
const scrollBarLeft = scrollBarWidth * scrollRatio
this.setData({
scrollBarLeft: scrollBarLeft,
});
},
})
问题
- scroll滚动距离的计算返回的值有差异,可能达不到滚动到底或者滚动到头,存在一定的距离差异。
- 上图实现效果,第一列固定展示通过position: sticky;实现,但包裹元素的宽度要给固定值,也就是说每一个item元素的宽度要通过设计稿先固定设置(rpx适配),然后外层容易的宽度通过item数量 * 固定宽度,否则会发现刚开始吸左,滚动到最后不吸左了。
后续准备通过wxs实现,到时候对比一下性能和实现的代码量