我喜欢这段代码的工作原理,但无论如何我都无法理解为什么它可以工作?
这是 jfidddle
代码如下:
jQuery(document).ready(function($) {
clone = $('div').clone();
$('div').after(clone);
$('div:last').hide();
offset = $('div:first').offset();
var fromtop = offset.top;
$(document).scroll(function() {
doc = $(this);
dist = $(this).scrollTop();
if (dist >= fromtop) {
$('div:last').show();
$('div:first').css({
'position': 'fixed'
});
} else {
$('div:first').css({
'position': 'static'
});
$('div:last').hide();
}
});
});
我想我不明白 scrolltop 和 offset 是如何相互作用的,或者它们到底是什么,就像它们在页面上的真实位置一样。代码表示如果 ScrollTop(滚动条位置?)高于 div 的 offsettop 的值,则使 div 具有粘性。但是如果ScrollTop是滚动条的位置,在div在页面顶部之前,滚动条位置有时可能低于div的位置是不是真的?位于页面顶部(offsettop 为 0?)——并且仅位于页面顶部,之前从未出现过——这使得 offsettop 的值小于 scrolltop 的值是什么意思?
真的很困惑,我不想只是复制代码而不理解它到底在做什么。
最佳答案
scroll Top 实际上是页面“向上”移动了多少像素(或者你向下移动了多少像素)
基本上所有发生的事情都是 .offset
查看“粘性”菜单在页面下方(从页面顶部开始)的距离
当您滚动到那个点时,条形图会固定(基本上是相对于窗口而不是文档)
当您向上滚动时,它只会切换回文档中的位置。
为清楚起见
.offset = 200px say - this is how far down the document the sticky menu is
.scrollTop - is 0 when the page loads
当你向下滚动页面201px时
.scrollTop > .offSet -> so make the bar fixed (remember fixed is relative to the window - not the document)
如果向上滚动,则过程相反。
关于javascript - 有人可以解释为什么这段代码可以使 div 在滚动后保持在顶部吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20946123/