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;
}
}