实现微信原生小程序自定义滚动条
<view class="box">
<scroll-view scroll-x="{{true}}" scroll-with-animation="{{true}}" bindscroll="spikeScroll" class="scroll">
<view class="item flex-shrink-0" wx:for="{{list}}" wx:key="index"></view>
</scroll-view>
<view class="segmentation" wx:if="{{list.length > 5}}">
<view>
<view class="scroll-bar__slide" style="width: {{barW}}rpx;left:{{percent}}rpx;"></view>
</view>
</view>
</view>
以上为index.wxml
const app = getApp()
Page({
data: {
content: "",
list: [1,2,3,4,5,6,7,8,9,10],
percent: 0,
barW: 0
},
onLoad() {
this.countCatWidth();
},
countCatWidth(){
//获取SelectorQuery对象实例
var query = wx.createSelectorQuery();
var that = this;
//获取某个节点信息
query.select('.item').boundingClientRect(res=>{
let sw = (res.width + 5)*that.data.list.length + 5;
that.setData({
barW: (40 / sw) * wx.getSystemInfoSync().windowWidth
})
}).exec();
},
spikeScroll(e){
let barW = (40 / e.detail.scrollWidth) * wx.getSystemInfoSync().windowWidth;
this.setData({
barW: barW,
percent: (40 / e.detail.scrollWidth) * e.detail.scrollLeft
})
},
})
以上为index.js
.box{
width: calc(100% - 60rpx);
height: 300rpx;
margin: 30rpx;
background: red;
position: relative;
}
.scroll{
display: flex;
flex-wrap: nowrap;
white-space: nowrap;
overflow-x: auto;
}
.item{
width: 20%;
height: 200rpx;
background-color: yellow;
display: inline-block;
margin-right: 20rpx;
}
.segmentation{
position: absolute;
left: calc(50% - 20rpx);
width: 40rpx;
bottom: 22rpx;
height: 4rpx;
background: #E3E3E3;
border-radius: 3rpx;
z-index: 99;
}
.segmentation >view{
width: 100%;
height: 100%;
position: relative;
}
.scroll-bar__slide{
position: absolute;
top: 0rpx;
left: 0rpx;
height: 100%;
background: #303032;
border-radius: 3rpx;
}
以上为index.wxss
综上所述,实现效果如下