效果如上图
下面是代码:
WXML:
1 <view class="contaier"> 2 <scroll-view class="nav-bar" scroll-x bindscroll="scroll"> 3 <!-- 要想使用flex布局实现横向滚动,就要在scroll-view里加一层容器包裹,并且使用子组件才会出现滚动效果 --> 4 <view class="nav-bar-wrap"> 5 <block wx:for="{{navbarArr}}" wx:key=‘key‘> 6 <view class="nav-bar-item" bindtap="onNavbarItem" data-id=‘{{item.id}}‘> 7 <image src="{{item.pic_url}}" /> 8 <text>{{item.name}}</text> 9 </view> 10 </block> 11 </view> 12 </scroll-view> 13 <view class="slider"> 14 <view class="slider-inside .slider-inside-location" style="left:{{left}}"></view> 15 </view> 16 </view>
WXSS:
1 .contaier { 2 position: relative; 3 height: 330rpx; 4 overflow : hidden; 5 background: #fff; 6 } 7 8 scroll-view { 9 white-space: nowrap; 10 border: 1px solid #ccc; 11 } 12 /* 去除滚动条 */ 13 ::-webkit-scrollbar { 14 display:none; 15 width:0; 16 height:0; 17 color:transparent; 18 } 19 .nav-bar-wrap { 20 display: flex; 21 flex-flow: column wrap; 22 height: 330rpx; 23 } 24 25 .nav-bar-item { 26 width: 187.5rpx; 27 display: flex; 28 flex-direction: column; 29 align-items: center; 30 padding-top: 28rpx; 31 } 32 33 .nav-bar-item image { 34 display: block; 35 height: 90rpx; 36 width: 90rpx; 37 margin: 0; 38 } 39 40 .nav-bar-item text { 41 margin-top: 5rpx; 42 line-height: 32rpx; 43 font-size: 25rpx; 44 } 45 46 .slider { 47 position: absolute; 48 bottom: 0rpx; 49 left: 50%; 50 transform: translateX(-50%); 51 width: 64rpx; 52 height: 6rpx; 53 border-radius: 3rpx; 54 background: #eee; 55 } 56 57 .slider-inside { 58 transform: translateX(-100%); 59 width: 42rpx; 60 height: 100%; 61 border-radius: 3rpx; 62 background-color: #f5d020; 63 } 64 /* 滑块定位 */ 65 .slider-inside-location { 66 position: absolute; 67 left: 65.625%; 68 }
JS:
1 Component({ 2 data: { 3 navbarArr: [],//icon图片对象数组 4 left: 0.65625 5 }, 6 attached() { 7 navbar.getNavBar(res => { 8 this.setData({ 9 navbarArr: res.data.data.list 10 }) 11 // console.log(this.data.navbarArr) 12 }) 13 }, 14 methods: { 15 onNavbarItem(options) { 16 const id = options.currentTarget.dataset.id 17 wx.navigateTo({ 18 url: `/pages/mysignup/mysignup?id=${id}`, 19 }) 20 }, 21 scroll(event) { 22 let scrollLeft = event.detail.scrollLeft + 375; 23 let scrllWidth = event.detail.scrollWidth; 24 let left = `${(scrollLeft) / scrllWidth * 100}%` 25 this.setData({ 26 left, //内部滑块 根据css设置 距离左边的百分比 27 }) 28 } 29 } 30 })
小小总结,如遇到同样需求,可以提问