小程序在滚动的tab里面点击的item,都能保持在中间。
小程序应用场景:
比如我要实现下面功能(如图),第一,点击任意的的tab_item,都能保持当前的点击的tab_item在中间, 第二可以根据其他页面传来的type(这个type可以自己定义。),滚动到相应的位置。

wxml
<scroll-view class="scroll-view_H"
scroll-left="{{scroll_left}}"
scroll-with-animation="true"
scroll-x="true">
<input class="search" placeholder="搜索"></input>
<view class="scroll-view-item_H">
<view wx:for="{{topArray}}"
bindtap="clickTitle"
data-type = "{{item.type}}"
class="{{type === item.type ?'active':''}}"
wx:key="index">{{item.title}}</view>
</view>
</scroll-view>
wxss
.scroll-view_H{
white-space: nowrap;
margin-bottom:16rpx;
}
.scroll-view-item_H{
display: inline-block;
width:70%;
}
.scroll-view-item_H>view{
display: inline-block;
width: 100px;
text-align: center;
height:67rpx;
line-height: 67rpx;
}
.scroll-view-item_H>view.active{
background: #FF6551;
border-radius: 50px;
color:#FFF;
}
.search{
border-radius: 50rpx;
border: 1px solid #828282;
width: 80px;
height:68rpx;
text-align: center;
display: inline-block;
margin:0 20px;
overflow: inherit;
}
js
Page({
/**
* 页面的初始数据
*/
data: {
topArray: [
{ title: '游览点', type: 2 },
{ title: '卫生间', type: 13 },
{ title: '视频监控', type: 11 },
{ title: '智能广播', type: 12 },
{ title: '出入口', type: 14 },
{ title: '观光车', type: 15 },
],
type: null, // 默认是类型2
scroll_left: 0, // 设置滚动条距离左边的位置。
},
// 点击头部title的处理事件
clickTitle(e) {
var that = this;
var index = e.currentTarget.dataset.index
var type = e.currentTarget.dataset.type
that.setData({
type: type
})
that.getMarkerList(type)
},
/**
* 页面传来的type。
*/
getMarkerList(page_tab_type) {
var that = this
var type = page_tab_type
that.Scroll_locatation(type)
},
/**
* 头部tab滚动定位的算法。
* type 要滚动那个位置。
* 100 这个是直接根据wxss写静态了,其实也可以动态的。
*/
Scroll_locatation(type) {
var that = this
var item_index = that.whitch_tab_item(type)
var scroll = 100 * item_index
that.setData({
type: type,
scroll_left: scroll
})
},
// 判断是那个tab_item
whitch_tab_item(type) {
var that = this
var tab_list = that.data.topArray
var item_index = null
tab_list.forEach((item, index) => {
if (item.type === type) {
item_index = index
}
})
return item_index
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
// 测试,如果默认是第二个
this.getMarkerList(13)
},
})
实现: 小程序的滚动到相应的位置还是比较简单。就是简单的利用到组件scroll-view和属性scroll-left, 如果是垂直的话,原理一样。
详情见api:https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html

浙公网安备 33010602011771号