我有一个代码可以在滚动到达底部之前获得300px时显示的内容!当达到底部时,我想在离开底部后获得300px时摆脱此消息!
当我在底部达到300px时它完全有效,但当我尝试向后滚动300px时它不起作用。
document.addEventListener('scroll', function(event) {
var docHeight = $(document).height(); // Document height
var winHeight = $(window).height(); // Window height
var minHeight = docHeight - winHeight; // Real document height
var curHeight = $(window).scrollTop(); // Display the height according to scrolling
$(window).scroll(function() {
//BEFORE
if(curHeight + 300 > minHeight) {
document.getElementById('copyrights').innerHTML = "Welcome to bottom";
}
//AFTER (doesn't work)
if(curHeight - 300 == minHeight - 300) {
document.getElementById('copyrights').innerHTML = "Good bye";
}
});
});
答案 0 :(得分:1)
你必须设置一个标志变量来保持你之前是否已经到底的状态,否则它只会在页面加载时说再见。第二次检查也应该是if(curHeight< = minHeight - 300)。总而言之,如下所示:
var scrolledToBottom = false;
document.addEventListener('scroll', function(event) {
var docHeight = $(document).height(); // Document height
var winHeight = $(window).height(); // Window height
var minHeight = docHeight - winHeight; // Real document height
var curHeight = $(window).scrollTop(); // Display the height according to scrolling
$(window).scroll(function() {
//BEFORE
if(curHeight + 300 > minHeight) {
document.getElementById('copyrights').innerHTML = "Welcome to bottom";
scrolledToBottom = true;
}
if (scrolledToBottom) {
//AFTER (doesn't work)
if (curHeight <= minHeight - 300) {
document.getElementById('copyrights').innerHTML = "Good bye";
}
}
});
});
答案 1 :(得分:0)
在您的示例中,$(window).scrollTop()
是从窗口顶部开始测量的当前滚动高度。要从窗口底部测量滚动位置,可以使用$(window).scrollTop() + $(window).height()
。
你可能想要一些看起来像这样的东西
$(window).scroll(function() {
var bottomOfWindow = $(window).scrollTop() + $(window).height();
if(bottomOfWindow < (document).height() - 300) {
// you are close to the bottom
}
});