实现uniapp tab栏

109 阅读1分钟

html ScroolLeft 代表 距离左边多长,点击前3个,不移动,点击第4个开始,减去前3个的偏移量,就是应该移动的距离

<scroll-view class="scroll-view_H" :scroll-x="true" :scroll-with-animation="true" :s :scroll-left="ScroolLeft">
    <view class="scrool_item_father">
	<view v-for="(item,index) in getCateList" :key="item.id" :class="      {'sec_scrool_item':true,'ov_four':getCateList.length>4,'sec_select_item':index==curNow}" @click="changeItem(index,item.id)" :id="'scr-'+index">{{item.name}}<view class="scr_di" v-show="index==curNow" :style="{ backgroundColor: navColor }">
     </view>
</view>
</view>
</scroll-view>

js

	mounted() {
	 let that = this
	 const query = uni.createSelectorQuery().in(this);
	 query.selectAll('.sec_scrool_item').boundingClientRect(data => {
                 //获取class 为 sec_scrool_item 组合而成的数组
	              console.log(data, "dianji");
		      that.scrArr = data
	  }).exec();
	},
        //点击事件
     changeItem(index, itemId) {
        //mounted得到的数组
        let scrollItemWidth = this.scrArr
        //前3个的宽高 + padding
	let width_1 = scrollItemWidth[0].width + 20
	let width_2 = scrollItemWidth[1].width + 20
	let width_3 = scrollItemWidth[2].width + 20
        //前3个组合的偏移量
	let offsetWidth = width_1 + width_2 + width_3
        //前3个往后的偏移量
        let scrollLeft = 0
	for (let i = 0; i < scrollItemWidth.length; i++) {
		if (i < index) {
                scrollLeft += (parseFloat(scrollItemWidth[i].width) + 20)
		}
	}
	scrollLeft = scrollLeft - offsetWidth
        //如果点击前3个,则不移动
       if (scrollLeft < 0) {
		scrollLeft = 0
	  }
	 this.ScroolLeft = scrollLeft
      },

css

.scroll-view_H {
		white-space: nowrap;
	}


	.scrool_item_father {
		display: flex;
		align-items: center;
		border-radius: 5rpx;
	}

	.scrool_item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		border: 1rpx solid #ff194b;
		border-right: none;
		color: #ff194b;
	}

	//超出4个盒子后
	.ov_four {
		flex: none;
		padding: 10rpx;
	}

	//点击下载盒子
	.select_item {
		background-color: #ff194b;
		color: #FFFFFF;
	}

	//第二中
	.sec_scrool_item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		border-right: none;
		color: #ff194b;
		position: relative;
	}

	.sec_select_item {
		// background-color: #ff194b;
		// color: #FFFFFF;
	}

	.scr_di {
		position: absolute;
		width: 60rpx;
		height: 5rpx;
		left: 50%;
		bottom: 5rpx;
		transform: translateX(-50%);

	}