Shopify Expanse主题:实现完整头部与通知栏滚动后固定
实现完整头部与通知栏滚动后固定的解决方案
针对你需要让完整头部(含通知栏)在滚动一段距离后固定的需求,修改原有代码如下,覆盖仅固定导航栏的逻辑:
修改思路
- 同时监听通知栏和完整头部容器,滚动超过两者总高度时触发固定
- 添加占位元素避免头部固定后页面布局塌陷
- 确保固定元素层级足够高,避免被其他内容遮挡
JavaScript 代码
<script> // 获取通知栏和完整头部容器(请根据实际DOM结构调整类名) const announcementBar = document.querySelector('.announcement-bar'); const headerContainer = document.querySelector('.header-wrapper'); // 创建占位元素,用于填充头部固定后留出的空间 const placeholder = document.createElement('div'); placeholder.style.height = `${announcementBar.offsetHeight + headerContainer.offsetHeight}px`; placeholder.style.display = 'none'; headerContainer.after(placeholder); window.onscroll = function() { if(window.innerWidth > 768){ // 滚动阈值设为通知栏+头部的总高度 const scrollThreshold = announcementBar.offsetHeight + headerContainer.offsetHeight; const isScrolled = document.body.scrollTop > scrollThreshold || document.documentElement.scrollTop > scrollThreshold; if (isScrolled) { // 固定通知栏到顶部 announcementBar.style.position = 'fixed'; announcementBar.style.top = '0'; announcementBar.style.width = '100%'; // 固定头部到通知栏下方 headerContainer.style.position = 'fixed'; headerContainer.style.top = `${announcementBar.offsetHeight}px`; headerContainer.style.width = '100%'; // 显示占位元素 placeholder.style.display = 'block'; } else { // 恢复初始布局 announcementBar.style.position = 'static'; headerContainer.style.position = 'static'; placeholder.style.display = 'none'; } } else { // 移动端恢复默认布局,避免冲突 announcementBar.style.position = 'static'; headerContainer.style.position = 'static'; placeholder.style.display = 'none'; } } </script>
CSS 代码
@media only screen and (min-width: 768px){ /* 确保固定后的元素层级最高,添加阴影增强视觉 */ .announcement-bar, .header-wrapper { z-index: 9999; transition: all 0.3s ease; /* 可选:添加平滑过渡效果 */ } /* 移除原有代码中冲突的样式 */ .header-item--compress-nav { display: none !important; } .header-wrapper--compressed .site-header__element--sub{ transform: none !important; } }
注意事项
- 若网站中通知栏或头部的类名与上述代码不符,请替换为实际DOM中的类名
- 占位元素的高度会自动计算,确保页面滚动时不会出现内容跳动
- 可根据需求调整
transition属性,实现固定/恢复的平滑动画效果
内容的提问来源于stack exchange,提问作者Campy
相关产品推荐
相关产品推荐

