滚动时实现多高度章节div依次堆叠固定顶部的技术问询
实现可变高度章节滚动堆叠固定效果
解决思路
要让不同高度的章节滚动时依次堆叠固定在顶部,核心是动态计算每个章节的实际渲染高度,再根据前面所有章节的总高度,实时调整每个sticky元素的top值——后续章节的top设为前面章节总高度的负值,就能实现堆叠效果。
完整实现代码
HTML(给章节统一添加标识类)
<div class="container"> <div class="sticky-section bg-red-400"> <h1> Chapter 1 div – big height big height big height big height big height big height </h1> </div> <p> Here text – here text - Here text – here textHere text – here textHere text – here textHere text – here text Here text – here text - Here text – here textHere text – here textHere text – here textHere text – here textHere text – here text - Here text – here textHere text – here textHere text – here textHere text – here textHere text – here text - Here text – here textHere text – here textHere text – here textHere text – here textHere text – here text - Here text – here textHere text – here textHere text – here textHere text – here text </p> <div class="sticky-section bg-green-400"> <h1> Chapter 2 div – biggest height biggest heightbiggest heightbiggest heightbiggest height heightbiggest heightbiggest heightheightbiggest heightbiggest heightheightbiggest heightbiggest height </h1> </div> <p> More words – more words - More words – more words - More words – more words - More words – more words - More words – more words - More words – more words - </p> <div class="sticky-section bg-yellow-400"> <h1>Chapter 3 div – small height </h1> </div> <p> Read this - Read this - Read this - Read this - Read this - Read this - Read this - Read this - Read this - Read this - Read this - </p> </div>
CSS基础样式
.container { position: relative; } .sticky-section { position: sticky; z-index: 10; width: 100%; top: 0; /* 初始值,后续JS动态调整 */ } .bg-red-400 { background: #f87171; } .bg-green-400 { background: #4ade80; } .bg-yellow-400 { background: #fbbf24; }
JavaScript动态计算逻辑
const sections = document.querySelectorAll('.sticky-section'); function updateStickyPositions() { let totalPrevHeight = 0; // 第一个章节固定在顶部 sections[0].style.top = '0px'; totalPrevHeight += sections[0].offsetHeight; // 从第二个章节开始,设置top为前面所有章节总高度的负值 for (let i = 1; i < sections.length; i++) { sections[i].style.top = `-${totalPrevHeight}px`; totalPrevHeight += sections[i].offsetHeight; } } // 页面加载完成后初始化 window.addEventListener('load', updateStickyPositions); // 窗口尺寸变化时重新计算(适配响应式高度变化) window.addEventListener('resize', updateStickyPositions); // 滚动时也触发(防止内容动态加载导致高度变化) window.addEventListener('scroll', updateStickyPositions);
要点解释
- 获取实际高度:用
offsetHeight获取章节的真实渲染高度,包含内边距、边框,能准确适配内容和屏幕尺寸变化带来的高度差异。 - 累计高度调整top:逐个累加前面章节的高度,把后续章节的
top设为负的累计值,这样滚动时后面的章节会“粘”在前面章节的下方,形成堆叠效果。 - 多事件监听:覆盖页面加载、窗口缩放、滚动三个场景,确保任何导致高度变化的操作都能重新计算位置,保持效果稳定。
滚动页面到最底部时,三个章节会按照预期效果横向堆叠在顶部。
内容的提问来源于stack exchange,提问作者Boq7
相关产品推荐
相关产品推荐

