概述
在tabs中有时候我们需要制作一个切换的效果,本身u-tabs这个组件已经能满足大多数的需求,但是该组件不够灵活,于是抽时间自己做了一个scroll-view切换的效果:
下面是上图的效果的代码:
<template>
<view>
<view class="demo">
<scroll-view class="scroll-view_H" scroll-x="true" @scroll="scroll" :scroll-left="scrollLeft"
scroll-with-animation="true">
<view @click="tabClick(index)" v-for="(item,index) in list" :id="'item-id-'+index" :key="index"
:class="['scroll-view-item_H',current==index?'active':'']">{{item.name}}</view>
</scroll-view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [{
name: 'zhangsan'
},
{
name: 'lisi'
},
{
name: 'wanger'
},
{
name: 'mazi'
},
{
name: 'zhangsn1'
},
{
name: 'lsii1'
},
{
name: 'lsii1'
},
{
name: 'lsii1'
},
{
name: 'lsii1'
}
],
scrollLeft: 0,
current: 0,
parentLeft: 0,
componentWidth: 0,
tabQueryInfo: [],
currentIndex: 5
}
},
methods: {
scroll(e) {
},
async init() {
const res = await this.$u.getRect('.demo');
this.parentLeft = res.left;
// tabs组件的宽度
this.componentWidth = res.width;
let query = uni.createSelectorQuery().in(this);
for (let i in this.list) {
query.select(`#item-id-${i}`).fields({
size: true,
rect: true
})
}
query.exec(
function(res) {
this.tabQueryInfo = res;
this.scrollByIndex();
}.bind(this)
);
},
scrollByIndex() {
let tabInfo = this.tabQueryInfo[this.current];
let tabWidth = tabInfo.width;
console.log(tabInfo)
console.log(tabWidth)
console.log(this.componentWidth)
let offsetLeft = tabInfo.left - this.parentLeft;
let scrollLeft = offsetLeft - (this.componentWidth - tabWidth) / 2;
console.log(scrollLeft)
this.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft;
},
tabClick(e) {
this.current = e;
this.scrollByIndex();
this.$nextTick(() => {
})
}
},
onReady() {
this.init();
}
}
</script>
<style lang="scss" scoped>
.demo {
width: 700rpx;
margin: 0 auto;
height: 80rpx;
background: #ccc;
.scroll-view_H {
white-space: nowrap;
.scroll-view-item_H {
display: inline-block;
width: 25%;
text-align: center;
line-height: 80rpx;
&.active {
background: #01B90B;
color: #fff;
}
}
}
}
</style>
最后
以上就是现实战斗机为你收集整理的uview tabs切换让item始终居中的全部内容,希望文章能够帮你解决uview tabs切换让item始终居中所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复