不等高左右侧边栏粘性滚动实现:底部对齐后同步滚动方案咨询
实现方案
核心问题说明
原有代码的问题主要是两点:
- 滚动位置判断用了全等
==,滚动时的步长不是连续1px变化,很容易无法命中触发条件 - 没有统一处理样式的添加/移除逻辑,状态切换时会残留之前的样式配置
完整可运行代码
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <div class="row" id="content-row"> <div class="col-lg-8 container-left"> grid view scroll with fixed header and footer Scrollable grid view with fixed headers and footer how do I make elements fixed on screen and post scroll only <!-- 可自行添加内容测试高度差 --> </div> <div class="col-lg-4 container-right"> grid view scroll with fixed header and footer Scrollable grid view with fixed headers and footer how do I make elements fixed on screen and post scroll only grid view scroll with fixed header and footer Scrollable grid view with fixed headers and footer how do I make elements fixed on screen and post scroll only <!-- 可自行添加内容测试高度差 --> </div> </div> <div class="col-lg-12 pop_block"> Scrollable grid view with fixed headers and footer how do I make elements fixed on screen and post scroll with fixed headers and footer how do I make elements fixed on screen and post scroll only </div> </div>
CSS
.wrapper{ max-width: 1200px; margin: 0 auto; } .container-left, .container-right { position: relative; } .sticky-bottom { position: sticky !important; bottom: 0 !important; }
JS
function sticky_relocate() { // 先重置所有样式,避免状态残留 $('.container-left, .container-right').removeClass('sticky-bottom'); var scrollTop = $(window).scrollTop(); var windowHeight = $(window).height(); var windowBottom = scrollTop + windowHeight; var $left = $('.container-left'); var $right = $('.container-right'); var rowTop = $('#content-row').offset().top; var leftHeight = $left.outerHeight(true); var rightHeight = $right.outerHeight(true); var maxHeight = Math.max(leftHeight, rightHeight); var rowBottom = rowTop + maxHeight; // 右侧更高:左侧做底部吸附 if (rightHeight > leftHeight) { if (windowBottom >= rowTop + leftHeight && windowBottom < rowBottom) { $left.addClass('sticky-bottom'); } } // 左侧更高:右侧做底部吸附 else if (leftHeight > rightHeight) { if (windowBottom >= rowTop + rightHeight && windowBottom < rowBottom) { $right.addClass('sticky-bottom'); } } } $(function() { // 滚动、窗口尺寸变化、页面加载时都触发计算 $(window).on('scroll resize', sticky_relocate); sticky_relocate(); });
效果说明
- 短列的底部滚动到视口底部后会自动吸附固定,长列继续正常滚动
- 当长列的底部滚动到视口底部时,两列解除吸附状态,同步跟随页面滚动
- 支持窗口尺寸变化自动适配,不会出现偏移问题
内容的提问来源于stack exchange,提问作者SRINIVASAN K T
相关产品推荐
相关产品推荐

