繁体   English   中英

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

[英]How to detect if browser window is scrolled to bottom?

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

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

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

更新了所有主要浏览器支持的代码(包括 IE10 和 IE11)<\/h1>
 window.onscroll = function(ev) { if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) { alert("you're at the bottom of the page"); } };<\/code><\/pre>

当前接受的答案的问题是window.scrollY<\/code>在 IE 中不可用。

这是mdn<\/a>关于 scrollY 的引用:

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

还有一个工作片段:

mac的注意事项<\/h3>

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

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

<\/blockquote>"

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

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");
    }
};

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

这有效

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");
    }
}

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

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

wrapper.onscroll = function (evt) {
  if (wrapper.scrollTop + window.innerHeight >= wrapper.scrollHeight) {
    console.log('reached bottom!');
  }
}
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

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

希望这对某人有用。

在这里,有一个小提琴;)<\/a>

    <!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>
$(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");
    }

}

如果你喜欢 jquery

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

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

新的解决方案。

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

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});

令人惊讶的是,没有一个解决方案对我有用。 我认为这是因为我的css<\/code>搞砸了,并且body<\/code>在使用height: 100%<\/code>时没有环绕所有内容(还不知道为什么)。 然而,在寻找解决方案时,我想出了一些很好的东西......基本上相同,但也许值得一看 - 我是编程新手,如果它的速度同样慢,支持较少或类似的东西,我很抱歉那...

window.onscroll = function(evt) {
  var check = (Element.getBoundingClientRect().bottom - window.innerHeight <= 0) ? true : false;
  if (check) { console.log("You're at the bottom!"); }
};
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

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

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

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

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

if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {}<\/code>

"

使用 vanilla javascript 的最简单方法

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

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

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')
    }
})

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

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

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

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

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

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

此功能在您滚动时触发,然后您可以做一些您想做的事情

  window.onscroll = function() {scrolled()};
  function scrolled() {
    fixed = document.body.scrollTop > 20 || 
    document.documentElement.scrollTop > 20 ? 
      "Am Going Down" : "Am Going Up"
  }

我为移动设备和桌面制作了这个 function 试试吧,这对我有用,这里的一些评论不适用于移动/Android 设备,顺便说一句,谢谢你提出这个问题。 保持向上的编码员!

    window.addEventListener("scroll", function(el) {
    const scrollY = window.scrollY + window.innerHeight + 2;
    const bodyScroll = document.body.offsetHeight;

    console.log("Scroll Y : " + scrollY);
    console.log("Body : " + bodyScroll);

    if(scrollY >= bodyScroll){
      alert("Bottom Page");
    }
  })

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM