2016-07-27 56 views
0

我有一个代码在滚动到达底部之前得到300px时显示一些内容!当达到底部时,我想在离开底部后达到300px时摆脱此消息!在离开底部之后做一些300px的事

当我在底部之前达到300像素时,它完美地起作用,但当我尝试向后滚动300像素时它不起作用。

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

您没有说明哪部分代码不起作用。 – which1ispink

+0

刚刚编辑,对不起! =/ –

回答

1

你必须设置一个标志变量来保存你是否已经到了底部之前或不在状态,否则将只是说在页面加载时再见。第二次检查也应该是(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"; 
     } 
    } 
    }); 
}); 
+0

'scrolledToBottom = true'是一个变量吗? –

+0

是的。它在第一行定义为在页面加载时为false,并且当您第一次接近底部时将其设置为true。 – which1ispink

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 
    } 
}); 
相关问题