jQuery JQuery检测底部滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8220267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:13:17  来源:igfitidea点击:

JQuery Detect Scroll at Bottom

jquery

提问by Cristian

I wish to achieve content load when the user scrolls to the bottom of the page.

我希望在用户滚动到页面底部时实现内容加载。

I am having a problem. It works fine on desktop browsers but not on mobile. I have implemented a dirty fix to make it work on the iPhone, but is not optimal as it won't work on other sized mobile devices.

我有问题。它适用于桌面浏览器,但不适用于移动设备。我已经实施了一个肮脏的修复,使其在 iPhone 上工作,但不是最佳的,因为它不能在其他尺寸的移动设备上工作。

My website is www.cristianrgreco.com, scroll down to see the effect in action

我的网站是 www.cristianrgreco.com,向下滚动查看实际效果

The problem is adding the scroll and the height do not equal the height on mobile devices, whereas they do on desktop browsers.

问题是在移动设备上添加滚动条和高度不等于高度,而在桌面浏览器上却是这样。

Is there a way to detect for mobile browsers?

有没有办法检测移动浏览器?

Thanks in advance.

提前致谢。

Below is the code currently being used:

下面是当前使用的代码:

$(document).ready(function () {
        $(".main").hide().filter(":lt(3)").show();
        if ($(document).height() == $(window).height()) {
            // Populate screen with content
        }
        else if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
            window.onscroll = function () {
                if ($(document).height() - $(window).scrollTop() <= 1278) {
                    // At the moment only works on iPhone
                }
            }
        }
        else {
            $(window).scroll(function () {
                if ($(window).scrollTop() + $(window).height() >= $(document).height()) {                     
                    // Works perfect for desktop browsers
                }
            })
        }
})

采纳答案by Nick Malcolm

For anyone who looks here later, I solved this by adding height=device-heightto the metaviewport tag:

对于以后看这里的任何人,我通过添加height=device-heightmeta视口标签解决了这个问题:

<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0">

You can then carry on using $(document).scroll(function(){});

然后您可以继续使用 $(document).scroll(function(){});

This worked with iOS 5

这适用于 iOS 5

回答by Finbey

An improved jQuery version of the code

代码的改进 jQuery 版本

var scrollRefresh = {
    pastTop: false,
    pastBottom: false,
    previous: 0,
    bottom: function(callback) {
      var pBottom = $(window).height() + $(window).scrollTop() >= $(document).height();
      if(!this.pastBottom && pBottom) {
        callback($(window).height() + $(window).scrollTop());
        this.pastBottom = true;
      } else {
        if(!pBottom) this.pastBottom = false;
      }
      this.previous = $(window).scrollTop();
    },
    top: function(callback) {
      var pTop = $(window).scrollTop() < this.scrollPrevious && $(window).scrollTop <= 0;
      if(!this.pastTop && pTop) {
        callback($(window).scrollTop());
        this.pastTop = true;
      } else {
        if(!pTop) this.pastTop = false;
      }
      this.previous = $(window).scrollTop();
    }
  }

  $(window).scroll(function() {
    scrollRefresh.top(function(pos) {
      console.log("Loading top. " + pos);
      alert("scrolled to top"); //You should delete this line
    });
    scrollRefresh.bottom(function(pos) {
      console.log("Loading bottom. " + pos);
      alert("scrolled to bottom"); //You should delete this line
    });
  });

回答by Enigma Plus

If you can, you should really avoid trying to hit an exact number.

如果可以的话,你真的应该避免试图达到一个确切的数字。

Using Stelok's function above, you can test like this:

使用上面的 Stelok 函数,你可以这样测试:

if ($win.height() + $win.scrollTop() > (getDocumentHeight()-10)) {

It's a bit softer - the user may not have quite scrolled to the exact last pixel but thinks he/she is at the bottom.

它有点柔和 - 用户可能没有完全滚动到最后一个像素,但认为他/她在底部。

回答by tonatiuhnb

This is what worked for me:

这对我有用:

(window.innerHeight + window.scrollY) == $(document).height()

Found here: Javascript: How to detect if browser window is scrolled to bottom?

在这里找到: Javascript:如何检测浏览器窗口是否滚动到底部?

回答by bloke_zero

Using jquery and Strelok's getDocumentHeight()below (cheers!) I found the following worked pretty well. Testing for equality didn't work for me as the iPhone only registered a scroll value at the end of the slide which was actually greater than the document height:

使用getDocumentHeight()下面的jquery 和 Strelok (干杯!)我发现以下效果很好。相等性测试对我不起作用,因为 iPhone 仅在幻灯片末尾注册了一个滚动值,该值实际上大于文档高度:

$(window).scroll(function () {
  var docHeight = getDocumentHeight();         
  if ($(window).scrollTop() + $(window).height() >= docHeight) {
    // Do stuff
  }
});

回答by Strelok

Bullet proof way to get document height on all browsers:

在所有浏览器上获取文档高度的防弹方法:

function getDocumentHeight() {
    return Math.max(
        Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
        Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
        Math.max(document.body.clientHeight, document.documentElement.clientHeight)
    );
}

回答by Jamon Holmgren

Here is an aggregate of the other answers which works very well for me. It could be written as a jQuery plugin sometime.

这是其他答案的汇总,对我来说非常有效。有时可以将其编写为 jQuery 插件。

// Handles scrolling past the window up or down to refresh or load more data.
var scrolledPastTop = false;
var scrolledPastBottom = false;
var scrollPrevious = 0;

function getDocumentHeight() {
  return Math.max(
      Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
      Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
      Math.max(document.body.clientHeight, document.documentElement.clientHeight)
  );
}

function bottomScrollRefresh(callback) {
  var pastBottom = $window.height() + $window.scrollTop() > getDocumentHeight();
  if(!scrolledPastBottom && pastBottom) {
    callback($window.height() + $window.scrollTop());
    scrolledPastBottom = true;
  } else {
    if(!pastBottom) scrolledPastBottom = false;
  }
  scrollPrevious = $window.scrollTop();
}

function topScrollRefresh(callback) {
  var pastTop = $window.scrollTop() < scrollPrevious && $window.scrollTop() <= 0;
  if(!scrolledPastTop && pastTop) {
    callback($window.scrollTop());
    scrolledPastTop = true;
  } else {
    if(!pastTop) scrolledPastTop = false;
  }
  scrollPrevious = $window.scrollTop();
}

To use this in your code, add something like this:

要在您的代码中使用它,请添加如下内容:

window.onscroll = function() {
  topScrollRefresh(function(pos) {
      console.log("Loading top. " + pos);
  });
  bottomScrollRefresh(function(pos) {
    console.log("Loading bottom. " + pos);
  });
};

Works great for my PhoneGap/Cordova app.

非常适合我的 PhoneGap/Cordova 应用程序。

回答by Thinking

Though the question was asked 5 years ago, still it is more than relevant in today's UI/UX context. And I would like to add my two cents.

尽管这个问题是 5 年前提出的,但它在今天的 UI/UX 上下文中仍然非常重要。我想加上我的两分钱。

var element = document.getElementById('flux');
if (element.scrollHeight - element.scrollTop === element.clientHeight)
{
    // element is at the end of its scroll, load more content
}

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled

来源:https: //developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled

回答by tim peterson

you can also use an endless scroll plugin: https://github.com/fredwu/jquery-endless-scrollhttps://github.com/paulirish/infinite-scroll

您还可以使用无限滚动插件:https: //github.com/fredwu/jquery-endless-scrollhttps://github.com/paulirish/infinite-scroll

i'm using the endless scroll and it works great on my laptop and iphone

我正在使用无尽滚动,它在我的笔记本电脑和 iPhone 上运行良好

回答by Keith.Abramo

Have you added the meta tag for iphones which sets the content size to the viewport of the phone?

您是否为 iphone 添加了元标记,将内容大小设置为手机的视口?

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

EDIT:

编辑:

So I tried this on my phone (android, gingerbread) and the issue wasn't so much the code not working it was the content displayed does not force the page to scroll. As soon as I zoomed in and scrolled down more content dynamically loaded. You could try adding content until the content added is greater than $(window).height();

所以我在我的手机(android,姜饼)上尝试了这个,问题不是代码不起作用,而是显示的内容不会强制页面滚动。一旦我放大并向下滚动,就会动态加载更多内容。您可以尝试添加内容,直到添加的内容大于 $(window).height();