通过jQuery插件Theia Sticky Sidebar,可以实现智能侧边栏跟随固定范围浮动的效果。本文讲的是不用“theia-sticky-sidebar”也能实现侧栏跟随效果,不过根据我的使用发现有点小bug,自己根据需要自行选择吧。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery.min.js"></script> <script> $(function() { var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0)); var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0)); var maxY = footTop - $('#sidebar').outerHeight(); $(window).scroll(function(evt) { var y = $(this).scrollTop(); if (y > top) { if (y < maxY) { $('#sidebar').addClass('fixed').removeAttr('style'); } else { $('#sidebar').removeClass('fixed').css({ position: 'absolute', top: (maxY - top) + 'px' }); } } else { $('#sidebar').removeClass('fixed'); } }); }); </script> <style> body { margin: 10px auto; font-family: sans-serif; width: 500px; } div { border-radius: 5px; box-shadow: 1px 2px 5px rgba(0,0,0,0.3); border: 1px solid #ccc; padding: 5px; } #sidebarWrap { height: 1400px; width: 210px; float: right; position: relative; box-shadow: none; border: none; margin: 0; padding: 0; } #main { width: 270px; height: 4000px; } #footer { clear: both; margin: 10px 0; } #sidebar { width: 200px; height: 1300px; position: absolute; background: #ff0; } .bar1{height:300px;background: #f00;} .bar2{background: #0f0;height: 300px;} .bar3{background: #00f;height: 300px;} #header { height: 200px; margin-bottom: 10px; } #sidebar.fixed { position: fixed; top: 0; } #footer { height: 600px; }</style> <title>侧栏跟随</title> </head> <body> <div id="header">header</div> <div id="sidebarWrap"> <div id="sidebar"><div class="bar1">Sidebar</div><div class="bar2"></div><div class="bar3"></div></div> </div> <div id="main">Main</div> <div id="footer">footer</div> </body> </html>