小程序模板网

小程序实现自定义滚动条

发布时间:2020-05-14 10:10 所属栏目:小程序开发教程

在 「小程序」 中怎么实现这种横向滚动效果呢。

说起来也简单,直接上代码吧

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
      })
  },
 


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/25168.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询