先看效果图吧(点击标题5自动滚动到中间):
我研究出最简单的做法,会有瑕疵,点击的项滚动到中间不是很正中间,原因是根据屏幕的高度定制滚动间隔个数,或者是每个分类项高度误差影响不是很完美,但是至少简单能用,自己调整就可以用了,上代码:
1. shopCar.wxml
<view class="container">
<!--左侧分类导航 :
首先使用相对定位将导航固定在页面左边,如果有头部导航和底部导航的需要自己计算各个的高度再定位分类导航,
假设我的头部导航headHeight为66px,底部导航footHeight为48px,进行如下定位后scroll-view的高度也固定好了
scroll-y 纵向滚动,默认是true
scroll-with-animation 是否添加滚动效果,默认是true
scroll-into-view 需要滚动项的id名称(选中的项,id不能以数字开头)
-->
<scroll-view style="position: absolute;top: {{headHeight}}px;left: 0;bottom: {{footHeight}}px;z-index: 1;"
class="scroll-tab"
scroll-y
scroll-with-animation
scroll-into-view="{{scrollTop}}">
<view
class="cu-item {{active == index?'active':''}}"
id="{{item.id}}"
wx:for="{{list}}"
wx:key="index"
bindtap='tabClick'
data-index="{{index}}">
Tab标题-{{item.id}}
</view>
</scroll-view>
</view>
2. shopCar.wxss
.container .scroll-tab{
width: 200rpx;
background-color: darkgray;
}
.cu-item{
padding: 40rpx 10rpx;
border-left: 6rpx solid transparent;
}
.cu-item.active{
border-color: #b30565;
background-color: #ffffff;
}
3. shopCar.js
// pages/shopCar/shopCar.js
const App = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
headHeight:App.globalData.headHeight || 66,//头部导航高度
footHeight:App.globalData.footHeight || 48,//底部导航高度
active: 0,//选中项的下标
scrollTop: "",//选中项滚动的id名称
list: [],//分类列表
num:0//根据手机屏幕高度设置滚动偏差个数-间隔个数
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let that = this;
// 获取系统信息
wx.getSystemInfo({
success: function (res) {
// 获取可使用窗口高度
let clientHeight = res.windowHeight;
console.log("屏幕高度",clientHeight)
let num;
//当屏幕高度小于600时,设置滚动id数字减2
//例如点击的项id是item5,点击之后scrollTop变为item3,滚动之后item5距离顶部有两个项的距离
//以下根据自己的需求设置间隔个数(如果不设置个数,点击的项默认滚动到顶部)
if(clientHeight < 600){
num = 2;
}else if(clientHeight > 600 && clientHeight < 800){
num = 3;
}else{
num = 4;
}
that.setData({
num:num
})
}
});
//生成假数据分类列表
let list = [];
for (let i = 0; i < 50; i++) {
list[i] = {};//插入空对象
list[i].id = "item"+i;//再插入id并赋值
}
this.setData({
list: list
})
},
//点击分类切换
tabClick(e) {
var index = e.currentTarget.dataset.index;//点击的下标
var count = this.data.num;//间隔个数
var id = "item"+(index-count);//拼接id
//判断当前点击的位置小于间隔个数时,设置滚动id为第一个(优化:全部显示最前面几个分类)
if(count == 2 && index < 3 || count == 3 && index < 4 || count == 4 && index < 5){
id = "item0";
}
console.log("下标",index,"---分类id名称",id)
this.setData({
active: index,//设置选中
scrollTop: id//滚动的分类id
})
},
})
ps:没有对比就没有伤害,自己闲着无聊看到京东购物小程序里面的分类列表设计就想搞一个,但是没办法做到跟它一样的,怎么简单怎么来吧,百度了一天网上也没有找到京东那种写法,只能自己瞎搞了,我的手机屏幕比较长所以下面是点击的距离顶部4个间隔,只能根据需求自己调整吧。
0.0
版权声明:本文为qq_38337245原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。