本来一直做JAVA+HTML5开发,最近微信小程序比较火,就想研究研究一下,结果花了两天时间研究发现微信小程序的三层架构比较不错,数据动态绑定也比较好用,但是和传统开发相比,开始还是有些不太习惯,特别是不能用window 和 document对象。在动态样式控制上可能需要一段时间来熟悉。
开发过程中发现两层导航(底部+顶部)实现起来还比较麻烦,用微信本身提供的tabBar最多只能设置5个tab且不能左右滚动,做底部可以,但是顶部栏目太多的话就不行。
顶部table栏目太多则需要左右滚动,于是考虑使用scroll-view来实现,结果发现一个问题,也许是我还没有研究透,横向滚动的scroll-view的scroll-into-view属性设置无效,官方API中的描述是“值应为某子元素id,则滚动到该元素,元素顶部对齐滚动区域顶部”(这里也没说左边),那就只能换个思路,用scroll-left来实现滚动。结果又有个问题,那就是scroll-view手动滚动时会有很难看的滚动条,网上查了一下资料,在wxss文件添加 ::-webkit-scrollbar{width: 0;height: 0;color: transparent;} 可影藏,开发工具上有效果,iPhone无效果,android未测试。
碰到的以上问题基本解决后,实现起来也就相对轻松一点。一下是部分关键代码,完成代码下载地址:
index.js
var app = getApp()
var that = null;
Page({
data: {
topTable:
[
{
id: "table1",
name: "推荐"
},
{
id: "table2",
name: "热点"
},
{
id: "table3",
name: "视频"
},
{
id: "table4",
name: "社会"
},
{
id: "table5",
name: "问答"
},
{
id: "table6",
name: "娱乐"
},
{
id: "table7",
name: "图片"
},
{
id: "table8",
name: "健康"
},
],
currentTabId : "table1",
currentTabSwiperIndex:0,
scrollLeft:0,
winHeight:0
},
onLoad:function (options){
that = this;
wx.getSystemInfo({
success: function(res) {
that.setData({winHeight:res.windowHeight})
}
})
console.log(that.data.winHeight)
},
/**
* 顶部TAB点击
*/
tableTap: function (e) {
that.setData({
currentTabId: e.target.id,
currentTabSwiperIndex: e.target.dataset.index
});
//that.getInfoList(e.target.dataset.index,0);
},
/**
* 列表区域滑动
*/
onSwiper: function (e) {
var currentIndex = e.detail.current;
that.setData(
{
currentTabId: that.data.topTable[currentIndex].id
}
);
/**此处应scroll-info-view属性横向无效,只能用次方法处理,当当前table位置超过整个列表的1/2则设置scrollLeft无限大的值,让scroll-view的后半段显示出来,
*如果当前index小于1/2则设置scrollLeft为0,让scroll-view的前半段显示出来,
*此方法栏目多了也有一个问题,大家自己琢磨有何问题,7个栏目以下基本可以。
*/
if (currentIndex > this.data.topTable.length / 2) {
that.setData(
{
scrollLeft: that.data.scrollLeft + 150
}
);
} else {
that.setData(
{
scrollLeft: 0
}
);
}
},
})
index.wxml
<!--index.wxml-->
<view class="top-table">
<scroll-view class="scroll-view_table" scroll-x="true" scroll-left="{{scrollLeft}}">
<block wx:for="{{topTable}}" wx:key="{{id}}" wx:for-item="table">
<view id="{{table.id}}" class="table-coll {{currentTabId==table.id?'selected':''}}" data-index="{{index}}" bindtap="tableTap">
{{table.name}}
</view>
</block>
</scroll-view>
</view>
<swiper class="table-swiper" style="height:{{winHeight+'px'}}" current="{{currentTabSwiperIndex}}" duration="300" bindchange="onSwiper">
<block wx:for="{{topTable}}" wx:key="id" wx:for-item="table" >
<swiper-item>
{{table.name}} swipr{{index}}
</swiper-item>
</block>
</swiper>
可能存在很多问题,请各位大神指教。