我正在开发一个有粘性侧边栏的网站。侧边栏只会固定在滚动窗口上。
问题是,当我向下滚动窗口并到达页面底部时,侧边栏将与页脚重叠,因为侧边栏是固定的。
我希望,当用户到达页面底部时,侧边栏停止滚动,如果用户滚动到页面顶部,它应该再次开始滚动。
您可以查看下面的我的代码,也可以查看 fiddle here 。
脚本
<script>
$(window).scroll(function(){
var contPos = $('.sidebar').offset().top;
var containerHeight = $('.container').height();
var heightOfWindow = $('body').height();
var topOfWindow = $(window).scrollTop();
if (contPos < topOfWindow) {
$('.sidebar').css('margin-top',''+topOfWindow+'px');
}
});
</script>
HTML
<div class="header">Header</div>
<div class="sidebar">asd</div>
<div class="container">Contaier</div>
<div class="footer">Footer</div>
CSS
.header{height:100px; text-align:center; font-size:35px; color:#000; background:#999;}
.container{overflow:auto; padding:15px; background:#CCC; height:1000px; margin:0 0 0 300px;}
.sidebar{width:300px; height:700px; float:left; background:red;}
.footer{height:100px; text-align:center; font-size:35px; color:#000; background:#999;}
最佳答案
我猜你必须编写一段 JS 代码来检测侧边栏是否位于页面的顶部、底部或中间。然后你可以设置一个特定的CSS类“bottom”,“top”,..并在fixed
/absolute
之间设置正确的位置。
这是我的做法:
关于jquery - 当侧边栏到达页面底部时停止滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797595/