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


187

我需要检测用户是否滚动到页面底部。如果它们在页面底部,则当我在底部添加新内容时,我将自动将它们滚动到新底部。如果它们不在底部,则它们正在阅读页面上更高的先前内容,所以我不想自动滚动它们,因为它们想留在原处。

如何检测用户是滚动到页面底部还是滚动到页面较高?


1
> stackoverflow.com/a/42547136/621951 -这是一个在6角工作
居纳伊居尔泰金

Answers:


267
window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
};

观看演示


29
当html / body元素设置为100%(以便主体填充整个视口高度)时
不起作用

5
使用document.documentElement.scrollTop代替window.scrollYIE。不知道哪个版本的IE支持window.scrollY
Batandwa

3
在Chromium版本47.0.2526.73中不起作用在Ubuntu 14.04上构建,在基本OS 0.3.2(64位)上运行
K-SO的毒性在不断增加。

9
我使用document.body.scrollHeight而不是offsetHeight(在我的情况下,offsetHeight始终小于window.innerHeight)
Oliver

1
@KarlMorrison您可以使用浏览器尝试获得赏金奖励的答案(@Dekel)吗?
Basj

114

更新了所有主要浏览器支持的代码(包括IE10和IE11)

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

当前接受的答案的问题是 window.scrollY IE中不可用。

这是mdn关于scrollY 的报价:

为了实现跨浏览器的兼容性,请使用window.pageYOffset而不是window.scrollY。

和一个有效的代码段:

Mac的注意事项

根据@Raphaël的评论,由于偏移量很小,mac中存在问题。
以下更新的条件有效:

(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2

我没有机会进一步测试它,如果有人可以对这个特定问题发表评论,那将是很棒的。


确认可以使用FF,Chrome,IE10和Android版Chrome。谢谢@Dekel!
巴斯基

2
听起来可能很奇怪,仅在我的浏览器中我不足1像素,因此不会触发该条件。不知道为什么,必须添加额外的px使其起作用。
Sharjeel Ahmed

3
在Mac计算机上,下面的条件是不是因为小的偏移(〜1像素)的满足我们更新了状态,像这样(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2
拉斐尔

4
谢谢@Dekel!实际上,我们发现window.pageYOffset是在Mac上的浮动对象。我们的最终解决方案是(window.innerHeight + Math.ceil(window.pageYOffset + 1)) >= document.body.offsetHeight
拉斐尔(Raphaël)

2
在身体具有将高度设置为100%的样式的情况下不起作用
raRaRa18年

56

接受的答案对我不起作用。这样做:

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
      // you're at the bottom of the page
      console.log("Bottom of page");
    }
};

如果您希望支持较旧的浏览器(IE9),请使用别名window.pageYOffset,该别名具有更好的支持。


1
在IE10 / 11中不起作用。检查Dekel的答案(stackoverflow.com/questions/9439725/…),以获取IE支持。为我工作
Herr_Schwabullek '16

每次滚动时,其他答案都会触发console.log(),而不仅仅是在页面底部时。这个答案对我来说适用于Chrome。
Defcronyke

如果您摆脱了在ie或edge中不起作用的window.scrollY,这是一个不错的答案。替换为:(window.innerHeight + window.pageYOffset)> = document.body.scrollHeight
colemerrick

21

我在寻找答案,但没有找到确切的答案。这是一个纯Javascript解决方案,可在此答案发布时与最新的Firefox,IE和Chrome配合使用:

// document.body.scrollTop alone should do the job but that actually works only in case of Chrome.
// With IE and Firefox it also works sometimes (seemingly with very simple pages where you have
// only a <pre> or something like that) but I don't know when. This hack seems to work always.
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

// Grodriguez's fix for scrollHeight:
// accounting for cases where html/body are set to height:100%
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;

// >= is needed because if the horizontal scrollbar is visible then window.innerHeight includes
// it and in that case the left side of the equation is somewhat greater.
var scrolledToBottom = (scrollTop + window.innerHeight) >= scrollHeight;

// As a bonus: how to scroll to the bottom programmatically by keeping the horizontal scrollpos:
// Since window.innerHeight includes the height of the horizontal scrollbar when it is visible
// the correct vertical scrollTop would be
// scrollHeight-window.innerHeight+sizeof(horizontal_scrollbar)
// Since we don't know the visibility/size of the horizontal scrollbar
// we scroll to scrollHeight that exceeds the value of the
// desired scrollTop but it seems to scroll to the bottom with all browsers
// without problems even when the horizontal scrollbar is visible.
var scrollLeft = (document.documentElement && document.documentElement.scrollLeft) || document.body.scrollLeft;
window.scrollTo(scrollLeft, scrollHeight);

4
这几乎对我有用,但我不得不使用html / body设置为height:100%的情况,((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)而不是仅仅document.body.scrollHeight考虑
Grodriguez 2014年

1
@Grodriguez感谢您的信息!将来可能对我们有用!:-)
pasztorpisti 2014年

14

这有效

window.onscroll = function() {

    // @var int totalPageHeight
    var totalPageHeight = document.body.scrollHeight; 

    // @var int scrollPoint
    var scrollPoint = window.scrollY + window.innerHeight;

    // check if we hit the bottom of the page
    if(scrollPoint >= totalPageHeight)
    {
        console.log("at the bottom");
    }
}

如果您希望支持较旧的浏览器(IE9),请将window.scrollY替换为window.pageYOffset


1
这项工作将在2019年做出反应。正文高度为100%,HTML高度为100。使用Chrome,Safari,Firefox,Edge。
愤怒的猕猴桃

请注意:应更改命名-应该切换变量。因为scrollHeight显示总页面高度,而totalHeight显示当前滚动点,所以有点令人困惑。
弗拉基米尔·马顿

4

我刚刚开始研究这个问题,这里的答案对我有帮助,所以谢谢。我进行了一些扩展,以使代码可以安全地回到IE7:

希望这对某人有用。

在这里,有一个小提琴;)

    <!DOCTYPE html>
<html>
<head>
    <style>
        div {
            height: 100px;
            border-bottom: 1px solid #ddd;
        }

        div:nth-child(even) {
            background: #CCC
        }

        div:nth-child(odd) {
            background: #FFF
        }

    </style>
</head>

<body>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</body>

<script type="text/javascript">
console.log("Doc Height = " + document.body.offsetHeight);
console.log("win Height = " + document.documentElement.clientHeight);
window.onscroll = function (ev) {
    var docHeight = document.body.offsetHeight;
    docHeight = docHeight == undefined ? window.document.documentElement.scrollHeight : docHeight;

    var winheight = window.innerHeight;
    winheight = winheight == undefined ? document.documentElement.clientHeight : winheight;

    var scrollpoint = window.scrollY;
    scrollpoint = scrollpoint == undefined ? window.document.documentElement.scrollTop : scrollpoint;

    if ((scrollpoint + winheight) >= docHeight) {
        alert("you're at the bottom");
    }
};
</script>
</html>

有点作品。但这不是很准确。只要您位于底部的16px左右,它就会认为它已滚动到底部。
彼得·霍尔

4

如果您height: 100%在某个容器上进行设置<div id="wrapper">,则以下代码有效(已在Chrome中测试):

var wrapper = document.getElementById('wrapper');

wrapper.onscroll = function (evt) {
  if (wrapper.scrollTop + window.innerHeight >= wrapper.scrollHeight) {
    console.log('reached bottom!');
  }
}

3
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

这个答案将修复边缘的情况下,这是因为pageYOffsetdouble同时innerHeightoffsetHeightlong的,所以当浏览器给你的信息,你可能是一个像素短。例如:在页面底部,我们有

真正 window.innerHeight = 10.2

真正 window.pageYOffset = 5.4

真正 document.body.offsetHeight = 15.6

然后我们的计算结果变为:10 + 5.4> = 16这是错误的

为了解决这个问题,我们可以Math.ceilpageYOffset值进行处理。

希望有帮助。



2

您可以查看jquery的无限滚动:

http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/

假设您愿意使用jquery库并且不希望使用严格的纯JS方法,这听起来像您的要求。


2
尽管此链接可以回答问题,但最好在此处包括答案的基本部分,并提供链接以供参考。如果链接的页面发生更改,仅链接的答案可能会失效。
bobthedeveloper 2014年

@Hatsjoem他正在链接到插件。应该复制哪些“基本部分”?谁在乎答案“如果链接页面发生更改将变为无效”?如果链接断开,则表示该插件已终止并且不再存在-即使您在答案中添加了更多信息,该插件仍然无效。哎呀,仅链接的答案不一定很糟糕。
dcastro

@Hatsjoem另外,来自meta:“当引用的库位于众所周知的稳定位置时,这种答案通常是较差的答案,但仍然是一个答案:它说“使用此”。
dcastro 2014年

另外,如果无限滚动更改此URL,则Google可能仍然存在。关键是要使用该插件,因此,如果链接消失,则只是google search jquery无限滚动。您可能会找到所需的东西。
开庆

2

令人惊讶的是,没有一种解决方案对我有用。我认为这是因为我css一团糟,使用时并body没有包装所有内容height: 100%(尚不知道为什么)。但是,在寻找解决方案时,我想出了一些不错的东西...基本相同,但是也许值得一看-我是编程新手,所以很抱歉,如果它做得同样慢,受支持较少或类似那...

window.onscroll = function(evt) {
  var check = (Element.getBoundingClientRect().bottom - window.innerHeight <= 0) ? true : false;
  if (check) { console.log("You're at the bottom!"); }
};

2
$(document).ready(function(){
    $('.NameOfYourDiv').on('scroll',chk_scroll);
});

function chk_scroll(e)
{
    var elem = $(e.currentTarget);
    if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) 
    {
        alert("scrolled to the bottom");
    }

}

idk有不同的观点。但是公认的答案肯定会更好
Zihan Zhang

2
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

这段代码也适用于Firefox和IE。


1

使用defaultViewdocumentElement嵌入功能代码段:

const { defaultView } = document;
const { documentElement } = document;
const handler = evt => requestAnimationFrame(() => {
  const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)();
  hitBottom
    ? console.log('yep')
    : console.log('nope')
});
document.addEventListener('scroll', handler);
<pre style="height:110vh;background-color:fuchsia">scroll down</pre>



0

我必须想出一种方法(用Java)来系统地向下滚动,以寻找我不知道正确的XPath的组件(长话短说,所以就一起玩)。正如我刚才所说的,我需要在寻找组件时向下滚动,并在找到该组件或到达页面底部时停止。

以下代码段控制向下滚动到页面底部:

JavascriptExecutor js = (JavascriptExecutor) driver;
boolean found = false;
long currOffset = 0;
long oldOffset = 0;
do
{
    oldOffset = currOffset;
    // LOOP to seek the component using several xpath regexes removed
    js.executeScript("window.scrollBy(0, 100)");
    currOffset = (Long)js.executeScript("var offset = window.window.pageYOffset; return offset;");
} while (!found && (currOffset != oldOffset));

顺便说一句,在执行此代码段之前,窗口已最大化。


0

接受的答案对我不起作用。这样做:

const element = document.createElement('div');
document.body.appendChild(element);
document.addEventListener('scroll', () => {
    const viewportHeight = window.innerHeight;
    const distance = element.getBoundingClientRect().top;
    if (Math.floor(distance) <= viewportHeight) {
        console.log('yep')
    } else {
        console.log('nope')
    }
})
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.