原生微信小程序实现自定义滚动条

实现微信原生小程序自定义滚动条

<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

综上所述,实现效果如下

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值