You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现TabBar选中时边框变蓝、未选中时为棕色?

实现带边框切换效果的TabBar

核心思路

给Tab容器和Tab项设置默认棕色边框,通过active类切换选中Tab的边框颜色为蓝色,同时处理边框重叠问题,配合简单交互逻辑完成状态切换。


原生HTML+CSS+JS实现

1. 结构代码

<div class="tab-container">
  <div class="tab-item active">标签1</div>
  <div class="tab-item">标签2</div>
  <div class="tab-item">标签3</div>
</div>

2. 样式代码

/* 容器样式:底部设置默认棕色边框,避免Tab项底部边框重复 */
.tab-container {
  display: flex;
  border-bottom: 1px solid #a67c52;
}

/* Tab项基础样式:默认棕色边框,隐藏底部边框 */
.tab-item {
  padding: 8px 16px;
  border: 1px solid #a67c52;
  border-bottom: none;
  margin-right: 8px;
  cursor: pointer;
  background-color: #ffffff;
  transition: all 0.3s ease;
}

/* 选中状态:切换边框和文字颜色为蓝色 */
.tab-item.active {
  border-color: #1677ff;
  color: #1677ff;
}

3. 交互逻辑

// 获取所有Tab项
const tabItems = document.querySelectorAll('.tab-item');

// 给每个Tab项绑定点击事件,切换active类
tabItems.forEach(item => {
  item.addEventListener('click', () => {
    tabItems.forEach(tab => tab.classList.remove('active'));
    item.classList.add('active');
  });
});

Vue3项目实现

组件代码

<template>
  <div class="tab-container">
    <div 
      class="tab-item"
      :class="{ active: activeTab === 0 }"
      @click="activeTab = 0"
    >
      标签1
    </div>
    <div 
      class="tab-item"
      :class="{ active: activeTab === 1 }"
      @click="activeTab = 1"
    >
      标签2
    </div>
    <div 
      class="tab-item"
      :class="{ active: activeTab === 2 }"
      @click="activeTab = 2"
    >
      标签3
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
// 控制当前选中的Tab索引
const activeTab = ref(0);
</script>

<style scoped>
.tab-container {
  display: flex;
  border-bottom: 1px solid #a67c52;
}

.tab-item {
  padding: 8px 16px;
  border: 1px solid #a67c52;
  border-bottom: none;
  margin-right: 8px;
  cursor: pointer;
  background-color: #ffffff;
  transition: all 0.3s ease;
}

.tab-item.active {
  border-color: #1677ff;
  color: #1677ff;
}
</style>

注意事项

  • 颜色值可按需调整,示例中棕色为#a67c52、蓝色为#1677ff
  • 过渡动画transition: all 0.3s ease让切换更流畅,可按需移除或修改
  • 若需要Tab项底部显示边框,可调整容器和Tab项的边框逻辑,比如给容器加完整边框,Tab项用margin-left: -1px重叠边框

内容的提问来源于stack exchange,提问作者Mr.Robot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:35:23