滚动时调整粘性导航栏高度的实现问题
解决粘性导航栏滚动时高度无法修改的问题
我参考了粘性导航栏的实现方案,代码如下,给导航栏设置了固定高度后,想在滚动页面时让导航栏高度变小,于是给.sticky类添加了height属性,但由于#navbar的ID选择器优先级更高,设置未生效,请问该如何修改?
我的代码:
JavaScript
window.onscroll = function() { myFunction() }; var navbar = document.getElementById("navbar"); var sticky = navbar.offsetTop; function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else { navbar.classList.remove("sticky"); } }
CSS
#navbar { background-color: #333; height: 145px; overflow: hidden; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px; text-decoration: none; } .content { padding: 16px; } .sticky { height: 85px; position: fixed; top: 0; width: 100%; z-index: 1; } .sticky+.content { padding-top: 145px; }
HTML
<div id="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div>
解决方案
1. 提高.sticky选择器优先级(最直接)
将.sticky的选择器改为#navbar.sticky,组合选择器的优先级高于单独的#navbar,能成功覆盖高度属性:
#navbar.sticky { height: 85px; position: fixed; top: 0; width: 100%; z-index: 1; }
2. 使用!important(应急方案,不推荐)
在.sticky的height属性后添加!important,强制覆盖ID的样式:
.sticky { height: 85px !important; position: fixed; top: 0; width: 100%; z-index: 1; }
注意:!important会打乱CSS优先级规则,后期维护易引发样式冲突,非必要不使用。
3. 改用类作为初始样式(更优架构)
把初始的ID选择器换成类,让初始样式和粘性样式优先级一致,后定义的样式会自动覆盖前面的:
- 修改HTML:
<div class="navbar" id="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div>
- 修改CSS:
.navbar { background-color: #333; height: 145px; overflow: hidden; } .navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px; text-decoration: none; } /* 其他样式保持不变 */ .sticky { height: 85px; position: fixed; top: 0; width: 100%; z-index: 1; }
内容的提问来源于stack exchange,提问作者joshmrodg
相关产品推荐
相关产品推荐

