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

如何使用HTML、CSS、JS实现响应式导航栏激活标签切换

问题根因

  1. 代码拼写错误:JS中innerHTMl拼写错误,末尾L应为大写,正确写法是innerHTML
  2. 逻辑错误:点击事件中获取的是点击前旧激活元素的id设置位置,而非当前点击的目标元素id
  3. 类型不匹配:元素id为字符串类型,switch判断的case为数字类型,类型不一致导致分支不触发
  4. 动态创建style标签的实现方式冗余,容易引发样式优先级冲突,且会产生大量DOM冗余节点

修复方案

直接操作动画元素的内联样式top属性,内联样式优先级高于CSS类选择器,实现更简单可靠,无需动态创建style标签。

修复后完整代码

JavaScript

var links = document.getElementsByClassName('l')
var animationBox = document.querySelector('.animation')
for (var i = 0; i < links.length; i++) {
  links[i].addEventListener("click", function() {
    // 移除旧激活状态
    document.querySelector(".active").classList.remove("active")
    // 新增当前元素激活状态
    this.classList.add("active")
    // 根据当前激活元素id计算动画框位置
    animationBox.style.top = (parseInt(this.id) - 1) * 50 + 'px'
  })
}

CSS

body {
  background: #2c3e5e;
  font-family: sans-serif;
}

nav {
  display: block;
  background-color: #34495e;
  position: relative;
  margin: 100px auto 0;
  border-radius: 8px;
  font-size: 0;
  width: 220px;
  height: auto;
  box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.1);
}

nav a {
  line-height: 50px;
  color: white;
  text-transform: uppercase;
  position: relative;
  z-index: 1;
  text-decoration: none;
  font-size: 15px;
  display: block;
  text-align: center;
}

nav .animation {
  position: absolute;
  height: 50px;
  width: 100%;
  top: 0px;
  z-index: 0;
  background: #1abc9c;
  border-radius: 8px;
  transition: all .5s ease 0s
}

nav a:nth-child(1):hover~.animation {
  top: 0;
}

nav a:nth-child(2):hover~.animation {
  top: 50px;
}

nav a:nth-child(3):hover~.animation {
  top: 100px;
}

HTML

<nav>
  <a href="#" id="1" class="l active">Student BioData</a>
  <a href="#" id="2" class="l">Student Acadmics</a>
  <a href="#" id="3" class="l">Complaint Record</a>
  <div id='animation' class="animation"></div>
</nav>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 09:36:03