2016-07-27 54 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 
    } 
}); 
相關問題