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

解决Tab组件默认打开首标签但内容不显示问题(CSS+JS)

解决Tab组件默认显示第一个标签内容的问题

问题原因

所有.tabcontent元素默认被CSS设置为display: none,虽然你给第一个.tablinks按钮添加了active类,但没有执行显示对应内容的逻辑,所以内容仍处于隐藏状态。

解决方案一:直接设置第一个内容块的初始显示状态

修改第一个标签内容的HTML,添加style="display: block",强制其默认显示:

<div id="London" class="tabcontent" style="display:block">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

解决方案二:页面加载时触发标签切换函数

在页面末尾添加脚本,模拟点击第一个激活的按钮,调用openCity函数完成内容显示:

<script>
// 页面加载完成后触发第一个标签的点击事件
document.querySelector('.tablinks.active').click();
</script>

完整修改后的代码示例(以解决方案二为例)

<div class="tab">
  <button class="tablinks active" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// 页面加载完成后触发第一个标签的点击事件
document.querySelector('.tablinks.active').click();
</script>

<style>
body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}
</style>

内容的提问来源于stack exchange,提问作者Pretty Styles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:55:15