ChatGPT解决这个技术问题 Extra ChatGPT

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

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

如何检测用户是否滚动到页面底部,或者他们是否在页面上滚动得更高?

这个在Angular 6中工作-> stackoverflow.com/a/42547136/621951

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

看演示


当 html/body 元素设置为 100% 时不起作用(以便 body 填充整个视口高度)
对于 IE,使用 document.documentElement.scrollTop 而不是 window.scrollY。不确定 IE 的哪个版本(如果有)支持 window.scrollY
不适用于 Chromium 版本 47.0.2526.73 构建于 Ubuntu 14.04,在基本操作系统 0.3.2(64 位)上运行
我使用 document.body.scrollHeight 而不是 offsetHeight(在我的例子中,offsetHeight 总是比 window.innerHeight 小)
@KarlMorrison 你能用你的浏览器试试赏金答案(@Dekel)吗?
C
Community

更新了所有主要浏览器支持的代码(包括 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。

还有一个工作片段:

window.onscroll = function(ev) { if ((window.innerHeight + window.pageYOffset ) >= document.body.offsetHeight) { alert("你在页面底部"); } };
































<

















































< br>







mac的注意事项

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

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

我没有机会进一步测试它,如果有人可以评论这个特定问题,那就太好了。


听起来很奇怪,只有在我的浏览器中,我缺少 1 px,因此不会触发条件。不知道为什么,必须添加额外的几个像素才能使其工作。
在 Mac 计算机上,由于偏移量小(~1px),不满足以下条件,我们像这样更新了条件 (window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2
谢谢@Dekel!实际上,我们发现 window.pageYOffset 在 mac 上是一个浮点数。我们的最终解决方案是 (window.innerHeight + Math.ceil(window.pageYOffset + 1)) >= document.body.offsetHeight
不适用于主体具有将高度设置为 100% 的样式的情况
@Raphaël 的评论挽救了我的睡眠!在 mac 中有 1 px 的问题,他的评论真的帮我解决了!!谢谢你!上帝祝福你!
L
Lex

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

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,它的支持稍好一些。


在 IE10/11 中不起作用。检查 Dekel 的答案 (stackoverflow.com/questions/9439725/…) 以获得 IE 支持。为我工作
每次我滚动时,其他答案都会触发 console.log(),而不仅仅是当我在页面底部时。这个答案在 Chrome 上对我有用。
如果您摆脱在ie 或edge 中不起作用的window.scrollY,这是一个不错的答案。替换为: (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight
即使您将身体设置为 100% 的最小高度,这也有效。
同样,这似乎是最好的版本-也适用于 mac
p
pasztorpisti

我正在寻找答案,但没有找到确切的答案。这是一个纯 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);

这几乎对我有用,但我不得不使用 ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight) 而不仅仅是 document.body.scrollHeight 来解决 html/body 设置为 height:100% 的情况
@Grodriguez 感谢您提供信息!将来它可能会派上用场! :-)
您的第一条评论使我免于在 Firefox 控制台上与 document.body.scrollTop 进行无意义的斗争。谢谢。
I
Ifeanyi Amadi

这有效

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


这项工作将在 2019 年做出反应。身体 100% 高度,html 100% 高度值得。使用 chrome、safari、firefox、edge。
请注意:应该更改命名 - 应该切换变量。因为 scrollHeight 显示的是页面总高度,而 totalHeight 显示的是当前滚动点,所以有点混乱。
J
Jeremy Bernier

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

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

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

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

这个答案将修复边缘情况,这是因为 pageYOffsetdoubleinnerHeightoffsetHeightlong,所以当浏览器为您提供信息时,您可能是一个像素短。例如:在页面底部我们有

window.innerHeight = 10.2

window.pageYOffset = 5.4

document.body.offsetHeight = 15.6

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

要解决此问题,我们可以对 pageYOffset 值执行 Math.ceil

希望有帮助。


C
Craig Poole

我刚开始看这个,这里的答案对我有帮助,所以谢谢你。我已经扩展了一点,以便代码一直安全地回到 IE7:

希望这对某人有用。

Here, have a Fiddle ;)

    <!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 范围内,它就会认为它会滚动到底部。
D
Darshna Rekha

如果您对其他方法不满意,请尝试此方法。

window.onscroll = function() { 常量差异 = document.documentElement.scrollHeight - window.innerHeight;常量滚动位置 = document.documentElement.scrollTop; if (difference - scrollposition <= 2) { alert("页面底部!"); } }


Z
Zihan Zhang
$(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 不同的观点。但接受的答案肯定更好
E
Eka putra

如果你喜欢 jquery

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()) {
    // doSomethingHere();
  }
});

谁不喜欢 jQuery……
@JoshHabdas 浏览器
c
cnnr
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

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


C
CheeseFrog

新的解决方案。

一个问题源于缺少标准的主滚动元素。最近实施的 document.scrollingElement 可用于尝试克服此问题。下面是一个带有回退的跨浏览器解决方案:

function atEnd() {
    var c = [document.scrollingElement.scrollHeight, document.body.scrollHeight, document.body.offsetHeight].sort(function(a,b){return b-a}) // select longest candidate for scrollable length
    return (window.innerHeight + window.scrollY + 2 >= c[0]) // compare with scroll position + some give
}
function scrolling() {
    if (atEnd()) 
        //do something
}
window.addEventListener('scroll', scrolling, {passive: true});

有效,非常感谢
C
Coldark

令人惊讶的是,没有一个解决方案对我有用。我认为这是因为我的 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!"); }
};

v
vhs

使用嵌入了功能代码段的 defaultViewdocumentElement

常量 { defaultView } = 文档;常量 { 文档元素 } = 文档; const handler = evt => requestAnimationFrame(() => { const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)(); hitBottom ? console.log('yep') : console.log('nope') }); document.addEventListener('scroll', handler);

向下滚动


P
Possible 11

如上所述,代码可能不适用于所有设备和浏览器。以下是经过测试的工作代码,将与所有浏览器(Chrome、IE、Edge、Firefox 和 Safari)中的所有主要设备(iPhone、Android、PC)兼容。

window.onscroll = function(ev) { var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); if ((window.innerHeight + window.scrollY) >= pageHeight) { console.log("你在页面底部。"); } };

继续滚动页面直到结束...


O
Oussama Essamadi

您可以检查窗口高度和滚动顶部的组合结果是否大于主体

if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {}


P
PJately

我发现两个对我有用的解决方案:

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + document.documentElement.scrollTop ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })

和另一个:

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + window.pageYOffset ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })

我认为您交换了顶部和底部的术语。您的解决方案在顶部启动:-)
嘿@m3nda,您指的是哪个解决方案?对我来说,两者似乎都在底部开火......
我尝试了它们,并且在页面顶部(上部内容)时触发了它们,与底部相反(当您将整个页面滚动到末尾时)。我在 Chrome 和 Firefox 中都检查了一遍。顺便说一句,@Ifeanyi Amadi 的解决方案按预期工作。问候。
D
Derek Dawson

使用 vanilla javascript 的最简单方法

container.addEventListener('scroll', (e) => {
  var element = e.target;
  if (element.scrollHeight - element.scrollTop - element.clientHeight <= 0) {
    console.log('scrolled to bottom');
  }
});

h
human

我只是在我的页面底部放置一个小图像,加载 =“lazy”,这样浏览器只会在用户向下滚动时加载它。然后该图像触发一个返回真实图像的 php 计数器脚本

 <img loading="lazy" src="zaehler_seitenende.php?rand=<?=rand(1,1000);?>">

 <?php
 @header("Location: https://domain.de/4trpx.gif");

h
hfontanez

我必须想出一种方法(在 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));

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


Java 不是 JavaScript。
@miken32 如果您因为“Java 不是 Javascript”而否决了这个答案,那么您没有很好地查看代码。我在 Java 应用程序中调用 Javascript,但执行滚动的代码是 Javascript。