如何实现点击按钮时将指定区块滚动至固定Header下方?
解决固定Header下滚动到目标区块的适配问题
要解决固定Header下滚动位置无法适配的问题,核心是动态获取Header的实际高度,再计算目标区块的滚动位置,替代固定的100px值。
方案1:手动计算滚动位置(兼容性好)
修改JS代码,通过offsetHeight获取Header的真实高度,再定位目标区块的顶部位置,两者相减得到精准的滚动距离:
document.querySelector('.booking__button').addEventListener('click', () => { // 获取固定Header的高度 const headerHeight = document.querySelector('.header').offsetHeight; // 获取目标搜索区块的DOM元素 const targetElement = document.querySelector('.booking__search'); // 计算滚动位置:目标区块顶部位置 - Header高度 const scrollPosition = targetElement.offsetTop - headerHeight; // 执行滚动,可选添加平滑效果 window.scrollTo({ top: scrollPosition, behavior: 'smooth' }); });
方案2:使用scrollIntoView简化代码(现代浏览器推荐)
利用元素原生的scrollIntoView方法,配合marginTop参数直接让目标元素滚动到Header下方,代码更简洁:
document.querySelector('.booking__button').addEventListener('click', () => { const headerHeight = document.querySelector('.header').offsetHeight; document.querySelector('.booking__search').scrollIntoView({ behavior: 'smooth', block: 'start', marginTop: `${headerHeight}px` // 避开固定Header }); });
完整代码示例
HTML
<header class="header"></header> <main class="hero"></main> <section class="booking"> <div class="booking__module"> <button class="booking__button">booking</button> </div> <div class="booking__search"></div> </section> <section class="others"></section>
CSS
body { margin: 0; } .header { position: fixed; top: 0; left: 0; right: 0; height: 60px; background: #002164; } .hero { min-height: calc(100vh - 100px); background: #fff; } .booking__module { display: flex; justify-content: center; align-items: center; background: #BC0B3C; } .booking__search { height: 600px; background: #ccc; } .booking__button { height: 20px; margin: 40px; } .others { height: 200vh; }
JavaScript
// 推荐使用方案1,兼容更多浏览器 document.querySelector('.booking__button').addEventListener('click', () => { const headerHeight = document.querySelector('.header').offsetHeight; const targetElement = document.querySelector('.booking__search'); const scrollPosition = targetElement.offsetTop - headerHeight; window.scrollTo({ top: scrollPosition, behavior: 'smooth' }); });
修改后,无论Header高度如何变化(比如响应式调整),滚动位置都会自动适配,确保booking__search区块刚好显示在固定Header的下方。
内容的提问来源于stack exchange,提问作者user349069
相关产品推荐
相关产品推荐

