如何实现滚动左侧列时同步滚动右侧列并按需显示页脚
解决方案
核心实现思路
- 将右侧列设置为独立滚动容器,初始禁止页面body滚动
- 监听左侧列滚动事件,同步控制右侧列滚动位置,确保左右区域滚动都能展示右侧内容
- 监听右侧列滚动状态,滚动到底部后解除body滚动限制并显示页脚
修改后的完整代码
HTML
<div class="container"> <div id="left-column" class="left-column"> <!-- 左侧列长内容示例 --> <p>左侧内容行 1</p> <p>左侧内容行 2</p> <p>左侧内容行 3</p> <!-- 重复足够多行使左侧可滚动 --> <p>左侧内容行 100</p> </div> <div id="right-column" class="right-column"> <!-- 右侧列长内容示例 --> <p>右侧内容行 1</p> <p>右侧内容行 2</p> <p>右侧内容行 3</p> <!-- 重复足够多行使右侧可滚动 --> <p>右侧内容行 80</p> </div> </div> <footer id="page-footer" class="page-footer"> 页面页脚内容 </footer>
CSS
* { margin: 0; padding: 0; box-sizing: border-box; } body { overflow: hidden; /* 初始禁止body滚动 */ height: 100vh; } .container { display: flex; height: 100vh; } .left-column { width: 300px; background: #f0f0f0; overflow-y: auto; /* 左侧自身可滚动 */ padding: 20px; } .right-column { flex: 1; background: #fff; overflow-y: auto; /* 右侧独立滚动容器 */ padding: 20px; height: 100vh; /* 限制高度为视口,避免撑高body */ } .page-footer { display: none; /* 初始隐藏页脚 */ height: 100px; background: #333; color: #fff; align-items: center; justify-content: center; } /* 右侧滚到底后,允许body滚动并显示页脚 */ body.footer-visible { overflow: auto; } body.footer-visible .right-column { height: auto; /* 解除右侧高度限制,让body能滚动到页脚 */ } body.footer-visible .page-footer { display: flex; }
JavaScript
const leftCol = document.getElementById('left-column'); const rightCol = document.getElementById('right-column'); const body = document.body; // 监听左侧滚动,同步右侧滚动位置 leftCol.addEventListener('scroll', () => { const leftScrollRatio = leftCol.scrollTop / (leftCol.scrollHeight - leftCol.clientHeight); const rightScrollTarget = (rightCol.scrollHeight - rightCol.clientHeight) * leftScrollRatio; rightCol.scrollTop = rightScrollTarget; }); // 防抖处理,避免滚动事件频繁触发 function debounce(func, delay = 100) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); }; } // 检查右侧是否滚动到底部 const checkBottom = debounce(() => { const isBottom = rightCol.scrollTop + rightCol.clientHeight >= rightCol.scrollHeight - 10; // 留10px误差 if (isBottom) { body.classList.add('footer-visible'); rightCol.removeEventListener('scroll', checkBottom); } }); rightCol.addEventListener('scroll', checkBottom);
关键细节说明
- 右侧列初始设置
height:100vh和overflow-y:auto,成为独立滚动容器,不影响body滚动状态 - 左侧滚动时通过计算滚动比例同步右侧位置,保证左右滚动对应展示右侧内容
- 右侧滚到底后给body添加类,解除滚动限制并显示页脚,同时移除滚动监听避免重复操作
- 防抖函数优化滚动事件触发频率,提升页面性能
内容的提问来源于stack exchange,提问作者Oscar RoAh
相关产品推荐
相关产品推荐

