我计划重新创建 Medium.com 之类的侧边栏。这就是我现在所拥有的,但还远未结束。
打开下面的JSFiddle可以更好地理解;我希望执行以下操作:
- 当你向下滚动时,它突然粘在底部。如何让它在滚动时逐渐粘住?
- 因为它使用
position:fixed
,所以它会向右侧移动而不考虑布局。我该如何解决这个问题? - 当您向上滚动并且空间较小时,它会与标题重叠,如屏幕截图所示。同样,很可能是因为使用了
position:fixed
。
我该如何解决这个问题?我知道有粘性套件可以完成这项工作,但我无法使用任何插件。
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);
最佳答案
我会尽可能回答你的问题。这是edited Fiddle first .
至于你的问题:
- 突然粘到底部是因为元素不是页面的全长,所以固定位置粘到底部会导致它跳到那里。而我所做的更改使其粘在顶部,则不会有这种跳跃,因为滚动时该元素位于屏幕顶部,因此可以谨慎地固定在那里。
- 这是因为元素没有固定的
宽度
,设置position:fixed;
意味着元素宽度不再由父元素设置,而是由父元素设置查看端口。因此它会扩展以填充视口(viewport)中的所有宽度。 - 发生这种情况是因为当滚动回元素原始位置上方时,
position:fixed;
从未被删除,Js中更新的if语句现在删除了带有position:fixed;的类。
当滚动到其原始位置上方时。
更详细地了解我所做的更改。
我添加了一个 CSS 类,因此可以使用 .toggleClass
使函数更加简洁。
.docked-sidebar {
position: fixed;
top: 0;
}
我还更改了 if 语句的条件,以便它们起作用。使用 .offset().top;
获取侧边栏和页面顶部之间的距离,同时删除大多数其他不需要的变量。最后,我创建了 bool 变量(isDocked
),以便不会多次触发相同的条件。
var $right = $('#sidebar'),
isDocked = false,
initOffsetTop = $right.offset().top;
function scrollCheck() {
var scrollTop = $(window).scrollTop(),
offsetTop = $right.offset().top;
if (!isDocked && ((offsetTop - scrollTop) < 0)) {
$right.toggleClass("docked-sidebar");
isDocked = true;
} else if (isDocked && scrollTop <= initOffsetTop) {
$right.toggleClass("docked-sidebar");
isDocked = false;
}
}
为了像示例网站一样先粘到底部,然后粘到顶部,我建议检查 this question .
关于javascript - 滚动期间从底部粘性侧边栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41957586/