jQuery高度不等于scrollTop

时间:2015-01-09 21:54:27

标签: javascript jquery

在我的jquery中,我试图计算滚动条从底部到100px的时间,当它到达那里时,我将进行ajax查询(现在我正在做警报,你可以看到)。

$(document).on("scroll", function(e){
    var scrollHeight = $(document).height();
    var offset = $(document).scrollTop();
    console.log(scrollHeight);
    console.log(offset);
    if(scrollHeight - offset <= 100){
        alert("here");
    }
});

由于某种原因,我无法弄清楚它不起作用。如果我滚动到底部,我会假设height()等于scrollTop(),但它没有,这就是它显示的内容:

scrollHeight = 1923
offset = 998

我是否使用了错误的方法?

5 个答案:

答案 0 :(得分:7)

您需要使用window添加scrollTop的高度。 Link

$(document).on('scroll', function () {
    var docHeight = $(document).height(),
        scrollTop = $(document).scrollTop(),
        windowHeight = $(window).height();

    if (docHeight - (scrollTop + windowHeight) <= 100) {
        alert(docHeight - (scrollTop + windowHeight));
    }

});

答案 1 :(得分:1)

看起来您可能忘记减去窗格的可查看高度。我在这里的代码中做了类似的事情:

          var scrollPos = $('#viewable-div').height() - $('#scrolling-content').height();
          if ($("#scrolling-content").scrollTop() > (scrollPos - 100)) {
              //load more 
          }

答案 2 :(得分:0)

当您将元素完全向下滚动时,scrollHeight应该等于scrollTop + clientHeight。

如果元素没有滚动条,则scrollWidth / Height应该等于clientWidth / Height。

•当元素没有滚动条时,IE使scrollHeight等于内容的实际高度;而不是元素的高度。 scrollWidth是正确的,除了在IE8中,它关闭了5个像素。

•Opera提供奇数,不正确的值。

答案 3 :(得分:0)

您可以使用这样的声明

((container.scrollTop() + container.height() + detectionOffset) >=
         container.get(0).scrollHeight)

容器可以是document.body和detectionOffset将是100

答案 4 :(得分:0)

之前已经回答了几次,包括here

我正在使用的一段代码(即使在Opera上)也是如此:

$(window).on("scroll", function () {
            var scrollHeight = $(document).height();
            var scrollPosition = $(window).height() + $(window).scrollTop();
            if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
                /* Do something */
            }
       });