微信小程序实现tab标签页的切换及动态的选中下划线移动

微信小程序实现tab标签页的切换及动态的选中下划线移动

注意:当前是横向切换,纵向切换请点击:纵向切换tab

效果演示

微信小程序实现tab标签页的切换及动态的选中下划线移动_第1张图片

代码片段

代码片段链接如下:
微信小程序代码片段
可直接点击代码片段路径观看完整演示。

完整代码

wxml如下
<view class="top_nav">
	<scroll-view class='scroll_list' scroll-x scroll-with-animation scroll-left="{{nav.left}}">
		<view class="scroll_item scroll_item{{index}} {{nav.active == index ? 'active' : ''}}" data-idx="{{index}}" wx:for="{{nav.list}}" wx:key="id" bindtap='select'>
			{{item.name}}
		view>
		<view class="sub" style="width:{{nav.width}}px; left:{{nav.offsetLeft}}px;">view>
	scroll-view>
view>
<view class="content">
	<swiper current="{{nav.active}}">
		<swiper-item wx:for="{{nav.list}}" item-id="{{item.id}}" wx:key="id">{{item.name}}swiper-item>
	swiper>
view>
wxss如下
.top_nav{ width: 100%; height: 82rpx; line-height: 80rpx; border-bottom: 1px solid #ddd; background-color: #FFF; position: fixed; top: 0; left: 0; z-index: 3;}
.top_nav .scroll_list{ height: 82rpx; white-space:nowrap;}
.top_nav .scroll_item{ display: inline-block; padding: 0 10px; font-size: 14px; vertical-align: top;}
.top_nav .scroll_item.active{ color:#E4393C;}
.top_nav .sub{ width:56rpx; height: 4rpx; background-color: #E4393C; position: absolute; top:78rpx; transition: left .5s;}
.content{ padding-top: 84rpx; text-align: center; line-height: 80rpx; font-size: 28rpx;}
js如下
Page({
	data: {
		nav: {  //滚动导航
			list: [
				{ name: '热门', id: 0},
				{ name: '上衣女', id: 1},
				{ name: '上衣男', id: 2},
				{ name: 'T恤', id: 3},
				{ name: '短裙', id: 4},
				{ name: '长裙', id: 5},
				{ name: '连衣裙', id: 6},
				{ name: '夏季凉鞋', id: 7},
				{ name: '冬季短靴', id: 8},
				{ name: '包包饰品', id: 9},
				{ name: '休闲裤', id: 10},
				{ name: '西装', id: 11},
			],
			active: 0,  //当前选中的导航下标
			left: 0,    //滚动值
			width: 28,
			offsetLeft: 11
		},
	},
	onLoad(){
		let _this = this;
        wx.getSystemInfo({
            success: function (res) {
                //console.log('系统信息:', res);
				_this.setData({
					windowWidth: res.windowWidth
				})
            }
        });
	},
	//滚动导航 - 选中监听
	select: function(e){
		// console.log('当前导航:', e);
		let _this = this,
			nav = this.data.nav,
			idx = e.currentTarget.dataset.idx,
			width = nav.list[idx].name.length * 14,
			windowWidth = this.data.windowWidth,
			offsetLeft = e.target.offsetLeft;
		if (offsetLeft < windowWidth) {
			nav.left = width + 68 - windowWidth + offsetLeft;
		} else {
			nav.left = offsetLeft - windowWidth + width + 68;
		}
		wx.createSelectorQuery().select('.scroll_item' + idx).boundingClientRect(function(res){
			nav.active = idx;
			nav.width = res.width - 20;
			nav.offsetLeft = offsetLeft + 11;
			_this.setData({
				nav: nav,
			})
			//可在这调用接口获取相应tab页的数据
		}).exec();
	}
})

你可能感兴趣的:(微信小程序,小程序,tab)