微信小程序自定义scroll-view的实例代码

小程序自定义 scroll-view 滚动条

话不多说, 直接上效果图

效果图

微信小程序自定义scroll-view的实例代码

wxml代码

 <scroll-view scroll-x 
  class="scroll-view" 
  bindscroll="bindScroll">
 <block wx:for="{{arr}}" wx:key="index">
 <view class="scroll-item">scroll-view{{index}}</view> 
 </block>
 </scroll-view>
 
 <!-- 滚动条 -->
 <view class="slide">
 <view class='slide-bar'>
 <view class="slide-action" 
  style="width:{{slideWidth}}rpx; margin-left:{{slideLeft<=1 ? 0 : slideLeft+'rpx'}};">
 </view>
 </view>
 </view>
 

wxss代码

 page{
 height: 100vh;
 background: rgb(111, 80, 65)
 }
 .scroll-view{
 display: flex;
 width: 100%;
 white-space: nowrap;
 padding-top: 20rpx;
 } 

 .scroll-item:nth-child(1){
 margin-left: 40rpx;
 } 

 .scroll-item {
 display: inline-block;
 width: 550rpx;
 height: 463rpx;
 background: rgba(199, 180, 165);
 border-radius: 20rpx;
 margin-right: 30rpx;
 color: #fff;
 } 

 .slide{
 background:rgb(111, 80, 65);
 width:100%;
 padding-top:20rpx;
 }
 .slide .slide-bar{
 width:180rpx;
 margin:0 auto;
 height: 4rpx;
 background: rgba(255,255,255,.2);
 } 

 .slide .slide-bar .slide-action{
 height:100%;
 background:#fff;
 } 

js代码

 /**
 * 页面的初始数据
 */
 data: {
 arr: 10,
 slideWidth: '',
 slideLeft: ''
 },

 /**
 * 生命周期函数--监听页面加载
 */
 onLoad: function (options) {
 // 计算比例
 this.calcRatio();
 },

 /**
 * 计算比例
 */
 calcRatio() {
 var windowWidth = wx.getSystemInfoSync().windowWidth;
 // 计算列表总长度
 var totalLength = (this.data.arr * 580) + 40;
 // 计算滑块的比例
 var slideRatio = 180 / totalLength * (750 / windowWidth);
 /**
 * 屏幕总长度 / 列表总长度 = 滑块占滚动条长度的比例
 * 滑块占滚动条长度的比例 * 滚动列表的长度 = 滑块的宽度
 */
 var sliderWidth = 750 / totalLength * 180;
 this.setData({
 slideWidth: sliderWidth,
 totalLength: totalLength,
 slideRatio: slideRatio
 })
 },

 /**
 * 监听滚动
 */
 bindScroll(e) {
 this.setData({
 slideLeft: e.detail.scrollLeft * this.data.slideRatio
 })
 },

附:scroll-view可滚动视图区域

微信小程序自定义scroll-view的实例代码

总结