微信小程序scroll-view實現自定義滾動條

本文實例為大傢分享瞭微信小程序scroll-view實現自定義滾動條的具體代碼,供大傢參考,具體內容如下

html

<!-- 九宮格 -->
  <scroll-view class="my-grid" scroll-x="true" bindscroll="getleft">
    <view class="grid-item" wx:for="{{gridlist}}" wx:key="index">
       <text>{{item.name}}</text>
    </view>
  </scroll-view>
  <!--滾動條部分-->
  <view class="slide">
    <view class='slide-bar' >
      <view class="slide-show" style="width:{{slideWidth}}rpx; margin-left:{{slideLeft<=1 ? 0 : slideLeft+'rpx'}};"></view>
    </view>
</view>

js

Page({
  data: {
    slideWidth:'',//滑塊寬
    slideLeft:0 ,//滑塊位置
    slideRatio:'',
    windowWidth:'',
    gridlist:[
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
      {name:'傢樂福'},
    ]
  },
  onLoad: function() {
    var self = this ;
    var systemInfo = wx.getSystemInfoSync() ;
    self.setData({
      windowWidth:systemInfo.windowWidth
    });
    self.getRatio();
  },
  //根據分類獲取比例
  getRatio(){
    var self = this ;
    var _totalLength = self.data.gridlist.length * 150; //分類列表總長度
    var _ratio = 230 / _totalLength * (750 / this.data.windowWidth); //滾動列表長度與滑條長度比例
    var _showLength = 750 / _totalLength * 230; //當前顯示紅色滑條的長度(保留兩位小數)
    console.log(_totalLength,_ratio,_showLength)
    this.setData({
      slideWidth: _showLength,
      totalLength: _totalLength,
      slideRatio:_ratio
    })
  } ,
  getleft:function(e){
    this.setData({
      slideLeft: e.detail.scrollLeft * this.data.slideRatio
    })
  },
})

css

/* 九宮格樣式 */
.my-grid{
  width: 100%;
  height: 220rpx;
  background-color: #00bfff;
  white-space: nowrap;
}
.my-grid .grid-item{
  width:150rpx;
  text-align:center;
  display:inline-block;
  height:115rpx;
}
.slide{
  height:30rpx;
  background:#fff;
  width:100%;
  padding:14rpx 0 5rpx 0
}
.slide .slide-bar{
  width:230rpx;
  margin:0 auto;
  height:1.5px;
  background:#eee;
}
.slide .slide-bar .slide-show{
  height:100%;
  background-color:#ff6969;
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: