双向滚动时隐藏固定导航栏 仅回到页面顶部显示的jQuery实现问题
实现思路
你的需求核心是仅页面处于顶部区域时显示导航,只要离开顶部无论滚动方向如何都隐藏,不需要额外判断滚动方向,只需要监听滚动位置和预设的顶部阈值对比即可实现。
调整后完整代码
jQuery(function($){ // 定义顶部阈值,滚动距离小于该值判定为处于顶部区域 const topThreshold = 20; // 提前缓存导航栏DOM对象,避免每次滚动都重复查询,提升性能 const $navbar = $('#global-header-section'); $(window).scroll(function() { // 获取当前页面滚动距离 const currentScroll = $(this).scrollTop(); // 滚动距离小于阈值就显示导航,否则直接隐藏 currentScroll < topThreshold ? $navbar.show(20) : $navbar.hide(20); }); });
可选优化方案
如果想要更顺滑的显隐效果,推荐用CSS过渡实现,性能比jQuery的show/hide方法更好:
- 先添加对应CSS样式
#global-header-section { position: fixed; top: 0; left: 0; width: 100%; /* 定义显隐过渡动画 */ transition: transform 0.2s ease; } /* 导航栏隐藏状态类 */ #global-header-section.hide { transform: translateY(-100%); }
- 调整JS逻辑为切换类名即可
jQuery(function($){ const topThreshold = 20; const $navbar = $('#global-header-section'); $(window).scroll(function() { const currentScroll = $(this).scrollTop(); // 滚动距离超过阈值就添加隐藏类,否则移除 $navbar.toggleClass('hide', currentScroll >= topThreshold); }); });
内容的提问来源于stack exchange,提问作者Drez
相关产品推荐
相关产品推荐

