UniApp 实现炫酷导航栏:选中图标上移并隐藏文字

发布于:2025-02-15 ⋅ 阅读:(35) ⋅ 点赞:(0)

在移动应用开发中,导航栏是用户与应用交互的重要组成部分,一个美观且交互性强的导航栏能大大提升用户体验。本文将详细介绍如何使用 UniApp 实现一个独特的导航栏,当用户选中某个导航项时,对应的图标会上移并隐藏文字,下面我们就来一步步剖析这个实现过程。

实现效果概述

我们要实现的导航栏固定在页面底部,包含多个导航项,每个导航项由图标和文字组成。当用户点击某个导航项时,该导航项的图标会上移一定距离,同时文字隐藏,给用户带来流畅且有趣的交互体验。

模板部分(template)

<template>
  <!-- 导航栏容器 -->
  <view class="tab-bar">
    <!-- 循环渲染导航栏项 -->
    <view 
      class="tab-bar-item" 
      :class="{ 'active': currentIndex === index }" 
      v-for="(item, index) in tabBarList" 
      :key="index" 
      @click="handleTabClick(index)"
    >
      <!-- 图标容器 -->
      <view class="icon-container">
        <!-- 根据选中状态显示不同图标 -->
        <image 
          :src="currentIndex === index ? item.activeIcon : item.icon" 
          mode="aspectFit"
        ></image>
      </view>
      <!-- 文字容器,根据选中状态决定是否显示 -->
      <view class="text-container" :style="{ display: currentIndex === index ? 'none' : 'block' }">
        {{ item.text }}
      </view>
    </view>
  </view>
</template>

脚本部分(script)

<script>
export default {
  data() {
    return {
      // 当前选中的导航栏项索引
      currentIndex: 0,
      // 导航栏数据列表
      tabBarList: [
        {
          // 引用 static 文件夹下的未选中图标
          icon: '/static/logo/index.png', 
          // 引用 static 文件夹下的选中图标
          activeIcon: '/static/logo/index-s.png', 
          text: '首页'
        },
        {
          icon: '/static/logo/fen.png',
          activeIcon: '/static/logo/fen-s.png',
          text: '分类'
        },
        {
          icon: '/static/logo/my.png',
          activeIcon: '/static/logo/my-s.png',
          text: '我的'
        }
      ]
    };
  },
  methods: {
    // 处理导航栏项点击事件
    handleTabClick(index) {
      this.currentIndex = index;
    }
  }
};
</script>

样式部分(style)

<style scoped>
.tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.tab-bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  transition: all 0.3s;
}

.tab-bar-item.active .icon-container {
  transform: translateY(-10px); /* 图标上移 10px */
}

.icon-container {
  width: 24px;
  height: 24px;
  transition: transform 0.3s;
}

.icon-container image {
  width: 100%;
  height: 100%;
}

.text-container {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}
</style>

总结

通过以上的代码实现,我们成功地使用 UniApp 打造了一个具有独特交互效果的导航栏。这种选中图标上移并隐藏文字的设计,不仅增加了导航栏的视觉吸引力,还提升了用户与应用的交互体验。开发者可以根据实际需求调整图标、文字和动画效果,让导航栏更符合项目的整体风格。希望本文对你在 UniApp 开发中实现类似的导航栏有所帮助。

你可以根据实际情况对上述内容进行修改和完善,同时可以在 CSDN 博客中添加代码块高亮、图片展示等功能,让文章更加丰富和易读。

最后,祝大家元宵节快乐