非直接点击切换页面内Tabs时,为何无法显示激活样式?
解决Tabs组件切换时按钮激活样式不生效的问题
问题现象
直接点击Tab按钮时,按钮能正常显示active激活样式;但通过内容区的箭头div切换Tabs时,对应Tab按钮无法显示激活样式。
问题原因
原代码里evt.currentTarget.className += " active"是给触发点击的箭头div加激活样式,而非对应Tab按钮;同时初始页面加载时调用openCity(event, 'one')的方式错误,DOMContentLoaded触发时传入的event并非有效事件对象。
修复方案
修改JavaScript函数逻辑,根据目标城市名称找到对应Tab按钮并添加激活样式,同时修正初始加载的调用方式:
修改后的完整代码
<html lang="en"> <head> <style> .tab button:hover { background-color: #ffb100; } .tab button.active { background-color: #ffb100; } </style> </head> <body> <div class="container"> <div class="tab"> <!-- 补充原代码遗漏的One按钮 --> <button class="tablinks" onclick="openCity(event, 'one')">One</button> <button class="tablinks" onclick="openCity(event, 'two')">Two</button> <button class="tablinks" onclick="openCity(event, 'three')">Three</button> </div> <div id="one" class="tabcontent" style="display:none"> (I'm one) <div class="arrowright" onclick="openCity(event, 'two')">arrowright</div> </div> <div id="two" class="tabcontent" style="display:none"> (I'm two) <div class="arrowleft" onclick="openCity(event, 'one')">arrowleft</div> <div class="arrowright" onclick="openCity(event, 'three')">arrowright</div> </div> <div id="three" class="tabcontent" style="display:none"> (I'm three) <div class="arrowleft" onclick="openCity(event, 'two')">arrowleft</div> </div> </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"; } // 移除所有Tab按钮的active样式 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"; // 找到对应城市的Tab按钮并添加active样式 const targetTab = Array.from(tablinks).find(btn => btn.getAttribute('onclick').includes(cityName)); if (targetTab) { targetTab.className += " active"; } } // 初始加载激活第一个Tab document.body.addEventListener('DOMContentLoaded', function() { openCity(null, 'one'); }); </script> </body> </html>
关键修改点
- 补充原代码遗漏的
OneTab按钮,确保三个城市都有对应切换入口 - 替换原有的激活样式添加逻辑,改为根据
cityName匹配对应Tab按钮并添加样式 - 修正初始加载的调用方式,用匿名函数包裹避免传入无效事件对象
- 将HTMLCollection转为数组,使用
find()方法精准定位目标按钮
内容的提问来源于stack exchange,提问作者WALDO
相关产品推荐
相关产品推荐

