用uniapp写一个带动画特效的tabs切换
时间: 2023-05-17 13:04:43 浏览: 190
好的,以下是一个使用uniapp编写的带动画特效的tabs切换的示例代码:
<template>
<view class="tabs">
<view class="tab" :class="{active: activeIndex === 0}" @click="switchTab(0)">
<text>Tab 1</text>
</view>
<view class="tab" :class="{active: activeIndex === 1}" @click="switchTab(1)">
<text>Tab 2</text>
</view>
<view class="tab" :class="{active: activeIndex === 2}" @click="switchTab(2)">
<text>Tab 3</text>
</view>
<view class="indicator" :style="{transform: 'translateX(' + indicatorOffset + 'px)'}"></view>
</view>
</template>
<script>
export default {
data() {
return {
activeIndex: 0,
indicatorOffset: 0
}
},
methods: {
switchTab(index) {
this.activeIndex = index
this.animateIndicator()
},
animateIndicator() {
const tabWidth = uni.upx2px(100)
const offset = this.activeIndex * tabWidth
uni.createSelectorQuery().in(this).select('.indicator').boundingClientRect(rect => {
const indicatorWidth = rect.width
const indicatorOffset = offset + (tabWidth - indicatorWidth) / 2
this.indicatorOffset = indicatorOffset
}).exec()
}
}
}
</script>
<style>
.tabs {
display: flex;
justify-content: space-between;
align-items: center;
height: uni.upx2px(100);
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.tab {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
font-size: uni.upx2px(32);
color: #666;
transition: color 0.3s;
}
.tab.active {
color: #007aff;
}
.indicator {
position: absolute;
bottom: 0;
left: 0;
width: uni.upx2px(60);
height: uni.upx2px(4);
background-color: #007aff;
transition: transform 0.3s;
}
</style>
这个示例代码中,我们使用了uniapp提供的upx2px函数将设计稿中的尺寸转换为实际像素值,以适应不同屏幕的显示。在switchTab方法中,我们通过设置activeIndex来切换当前选中的tab,并调用animateIndicator方法来更新指示器的位置。在animateIndicator方法中,我们使用uni.createSelectorQuery获取指示器的宽度,然后根据当前选中的tab的位置计算出指示器应该移动的距离,并将其设置为indicatorOffset的值,从而实现动画效果。
阅读全文
相关推荐

















