【发布时间】:2017-01-31 12:27:01
【问题描述】:
我打算重新创建 Medium.com 之类的侧边栏。这就是我现在所拥有的,但远未结束。
打开下面的 JSFiddle 可以更好地理解;我希望执行以下操作:
- 当您向下滚动时,它突然卡在底部。如何让它在滚动时逐渐粘住?
- 因为它使用
position: fixed,所以它在不考虑布局的情况下向右侧移动。我该如何解决这个问题? - 当您向上滚动并且空间较小时,它会与标题重叠,如屏幕截图所示。同样,很可能是因为使用了
position: fixed。
我该如何解决这个问题?我知道有 Sticky-kit 可以工作,但我不能使用任何插件。
HTML:
<div class="container">
<div class="row">
<div class="col-xs-12">
Header and Menu is placed here.
<hr />
</div>
<div class="col-xs-8">
<p>This is the main body which the user would be scrolling infinitely as more data gets loaded on scroll.</p>
</div>
<div class="col-xs-4">
<div id="sidebar">
<p>
This is the sidebar which I want to stop when it reaches the bottom like the one shown in medium dot com
</p>
</div>
</div>
</div>
</div>
Javascript:
function scrollCheck() {
var $right = $('#sidebar'),
scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
docHeight = $(document).height(),
rightHeight = $right.height(),
distanceToTop = rightHeight - windowHeight,
distanceToBottom = scrollTop + windowHeight - docHeight;
if (scrollTop > distanceToTop) {
$right.css({
'position': 'fixed',
'bottom': (scrollTop + windowHeight > docHeight ? distanceToBottom + 'px' : '0px')
});
}
else {
$right.css({
'position': 'relative',
'bottom': 'auto'
});
}
}
$(window).bind('scroll', scrollCheck);
【问题讨论】:
-
请多解释一下
-
查看 medium.com 并注意边栏在底部越过而主要内容继续滚动时是如何粘住的。我想复制同样的效果。
-
我设法把它放到dock to the top on scrolling,但是让它在向下滚动时平滑地停靠到底部,然后像示例网站一样在向上滚动时切换回停靠到顶部要复杂得多然后我预料到了。
标签: javascript jquery