在tabs中有时候我们需要制作一个切换的效果,本身u-tabs这个组件已经能满足大多数的需求,但是该组件不够灵活,于是抽时间自己做了一个scroll-view切换的效果:
下面是上图的效果的代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131<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内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复