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

2020/10/18 20:21 · javascript ·  · 0评论

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

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

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

观看演示

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

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

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

这是mdn关于scrollY的报价

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

和一个有效的代码段:

Mac的注意事项

根据@Raphaël的评论,由于偏移量较小,mac中存在问题。

以下更新的条件有效:

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

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

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

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该别名具有更好的支持。

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

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

我刚刚开始研究这个问题,这里的答案对我有帮助,所以谢谢。我进行了一些扩展,以使代码可以安全返回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>

如果您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!');
  }
}
$(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");
    }

}
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价值

希望能有所帮助。

如果你喜欢jQuery

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

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

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

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

令人惊讶的是,没有一种解决方案对我有用。我认为这是因为我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!"); }
};
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

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

使用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>

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

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

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

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

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

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

和另一个:

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + window.pageYOffset ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })
本文地址:http://javascript.askforanswer.com/javascriptruhejianceliulanqichuangkoushifougundongdaodibu.html
文章标签:
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!