首页 前端知识 uni-app 页面横向点击居中

uni-app 页面横向点击居中

2024-10-17 10:10:57 前端知识 前端哥 24 293 我要收藏

在这里插入图片描述
uni-app 页面横向点击居中
1.使用scroll-view可滚动视图区域。用于区域滚动;
2.动态计算横向滚动条位置scroll-left。

以下是代码:

<template>
	<view class="mainbox">
		<view class="navbox">
			<scroll-view scroll-x="true" class="content-scroll" scroll-with-animation :scroll-left="scrollLeft">
				<view v-for="(vo,index) in catelist" :key="index" class="scroll-item navlist" :class="{active:navindex==vo.id}" @click.stop="changeTitle(vo.id,vo)">
					<view class="navname">{{vo.name}}</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>
<script>
export default {
	data(){
		return{
			catelist:[
				{id:'0',name:'全部'},
				{id:'1',name:'推荐'},
				{id:'2',name:'食品'},
				{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',name:'鞋包'},
				{id:'12',name:'电器'},
				{id:'13',name:'家装'},
				{id:'14',name:'医药'},
				{id:'15',name:'运动'},
				{id:'16',name:'男装'},
				{id:'17',name:'母婴'},
				{id:'18',name:'车品'},
			],
			navindex:'0',
			scrollLeft:0,
			contentScrollW: 0, // 导航区宽度
		}
	},
	onLoad() {
		let that = this;
		setTimeout(()=>{
			that.getScrollW();//业务需求中在分类列表加载完执行,加上延时作为测试页面展示。
		},1000)
	},
	methods:{
		// 获取标题区域宽度,和每个子元素节点的宽度以及元素距离左边栏的距离
		getScrollW() {
			let that = this;
			const query = uni.createSelectorQuery().in(that);
			query.select('.content-scroll').boundingClientRect(data => {
				// 拿到 scroll-view 组件宽度
				that.contentScrollW = data.width;
			}).exec();
			query.selectAll('.scroll-item').boundingClientRect(data => {
				let dataLen = data.length;
				for (let i = 0; i < dataLen; i++) {
					 // scroll-view 子元素组件距离左边栏的距离
					that.catelist[i].left = data[i].left;
					//  scroll-view 子元素组件宽度
					that.catelist[i].width = data[i].width
				}
			}).exec()
			setTimeout(function(){
				let index = that.catelist.findIndex(item => item.id == that.navindex);
				that.scrollLeft = that.catelist[index].left - that.contentScrollW / 2 + that.catelist[index].width / 2;
			},200)
		},
		changeTitle(index,obj){
			this.navindex = index;
			this.scrollLeft = this.catelist[index].left - this.contentScrollW / 2 + this.catelist[index].width / 2;
		},
	}
}
</script>
<style lang="less">
.mainbox{min-height:100vh;background:#fff;}
.content-scroll {
	white-space: nowrap;padding:2vw 3.2vw;box-sizing: border-box;height:12vw;
	.navlist{
		display: inline-flex;margin-right:3.2vw;padding:0 2.7vw;box-sizing: border-box;border-radius:1vw;
	}
	.active{
		background:rgba(255,49,49,0.1);color:#ff5000;
	}
}
转载请注明出处或者链接地址:https://www.qianduange.cn//article/19110.html
标签
评论
发布的文章

在C#中使用JSON

2024-11-04 10:11:05

JSON串

2024-11-04 10:11:57

JSON教程(非常详细)

2024-05-08 10:05:36

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!