CSS响应式顶部标签导航height从85px到unset过渡动画失效求解
问题原因
CSS transition 仅支持两个可计算的固定数值之间的属性过渡,height 从固定值 85px 切换到非固定值 unset/auto 时,浏览器无法计算中间过渡帧,因此动画失效。
最优解决方案:使用max-height替代height实现过渡
该方案改动最小、兼容性最好,无需调整核心业务逻辑,仅修改CSS+修正JS笔误即可:
核心修改逻辑
- 把原本绑定在
height上的过渡改到max-height属性 - 导航收起时设置
max-height: 85px,和你原本的固定导航高度对齐 - 导航展开时设置
max-height为一个远大于导航实际展开高度的值(示例用500px,可根据实际导航项数量灵活调整) - 移除原本
#routes-container的display: none配置,靠外层overflow: hidden隐藏超出高度的内容
完整可运行代码
修正后的JS代码(修正原变量名拼写错误)
function responsifyTopNavigator() { const nav = document.getElementById("topnav"); let navClassName = "topnav"; if (nav.className === "topnav") { navClassName += " responsive"; } nav.className = navClassName; }
修改后的CSS代码
* { margin: 0; padding: 0; } .topnav { position: fixed; overflow: hidden; top: 0; width: 100%; height: unset; max-height: 85px; /* 收起时的最大高度,对应原固定高度 */ background-color: #f0efe9; transition: max-height 0.3s ease-in; /* 过渡绑定到max-height,时长可自行调整 */ -webkit-transition: max-height 0.3s ease-in; -moz-transition: max-height 0.3s ease-in; -o-transition: max-height 0.3s ease-in; } .topnav #routes-container { display: flex; flex-direction: row; justify-content: flex-end; } .topnav a { float: left; display: block; height: 20px; padding: 35px 30px; font-size: 16px; text-align: center; text-decoration: none; color: #41403e; } .topnav a#toggle { display: none; } @media screen and (max-width: 1000px) { .topnav a { font-size: 16px; } /* 移除display: none,靠外层max-height隐藏内容 */ .topnav #routes-container { display: block; margin-top: 85px; } .topnav a#toggle { float: right; display: block; } } @media screen and (max-width: 1000px) { .topnav.responsive { position: relative; max-height: 500px; /* 只要大于导航实际展开高度即可,可自行调整 */ } .topnav.responsive a#toggle { position: absolute; right: 0; top: 0; } .topnav.responsive #routes-container a { float: none; text-align: left; } }
HTML代码无需改动
<div class="topnav" id="topnav"> <div id="routes-container"> <a href="#" class="active">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">5</a> </div> <a href="javascript:void(0);" id="toggle" onclick="responsifyTopNavigator()" > TOGGLE </a> </div>
可选优化
如果你的导航项数量不固定,担心max-height设置过大导致过渡速度不匹配,可以用JS动态计算导航展开后的实际高度,直接赋值给height属性再做过渡,动画精度会更高。
内容的提问来源于stack exchange,提问作者Raul
相关产品推荐
相关产品推荐

