Javascript Scroll事件

时间:2012-04-10 01:06:45

标签: javascript jquery scroll

在某些博客上,当您向页面底部滚动时,它们会有一个可以滑入页面右下角视图的DIV。

很多时候,在一篇博客文章中,你会在页面上看到评论部分开始的位置,他们将把这个DIV幻灯片放到视图中。

我试图复制这个,我看到有一个网站可以做到这一点,但它没有在评论附近做,而是使用下面的代码,你可以看到它在中途点左右。

Document height - the Window height / 2

所以它实际上离开了页面的一半。当我到达页面的评论部分时,我将如何进入视图,让我们说我的评论包含在ID为comments的DIV中

$(document).scroll(function () {
    var curPos = $(document).scrollTop();
    var docHeight = $(document).height() - $(window).height();
    if (curPos > (docHeight / 2)) {
      MoneyBox.show();
    } else {
      MoneyBox.hide();
    }
});

enter image description here

1 个答案:

答案 0 :(得分:3)

尝试比较scrollTop和div

的偏移量
$(document).scroll(function(){
    var curPos = $(document).scrollTop();

    var commentsPos = $('#comments').offset().top;

    if(curPos >= commentsPos) {
        MoneyBox.show();
    } else {
        MoneyBox.hide();
    }
});