简体   繁体   English

检查用户已在 Jquery 中滚动到底部 [代码不适用于 Chrome]

[英]check user has scrolled to the bottom in Jquery [code not working on Chrome]

I wanted to check user has scrolled to the bottom of the page or not with jquery.我想检查用户是否使用 jquery 滚动到页面底部。 I searched and find a solution which work perfectly on Microsoft Edge but it is not working fine on Google Chrome.我搜索并找到了一个在 Microsoft Edge 上完美运行的解决方案,但在 Google Chrome 上却无法正常运行。

 $(document).ready(function(){ $(window).scroll(function() { if($(window).scrollTop() + $(window).height() == $(document).height()) { alert("bottom!"); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="height: 4000px">Scroll down!</div>

Output in Microsoft Edge: Perfect as I wants. Microsoft Edge 中的输出:如我所愿。

Output in Google Chrome: In Google Chrome when i scroll to bottom and again scroll to top then it works but I don't want this.谷歌浏览器中的输出:在谷歌浏览器中,当我滚动到底部并再次滚动到顶部时,它可以工作,但我不想要这个。

Its working fine as expected on google chrome as well.它在谷歌浏览器上也按预期工作正常。 Check this检查这个

 $(document).ready(function(){ $(window).scroll(function() { if($(window).scrollTop() + $(window).height() == $(document).height()) { alert("bottom!"); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <div style="height: 4000px">Scroll down!</div>

If you want a pure javascript based solution then here you go :如果您想要一个基于纯 javascript 的解决方案,那么您可以:

 window.onscroll = function(ev) { if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) { alert("you're at the bottom of the page"); } };
 <div style="height:5000px"></div>

For compatibility on all browsers, try this method为了兼容所有浏览器,试试 这个方法

function getDocHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    );
}

Replace $(document).height() by this function and it's all good用这个函数替换$(document).height()就好了

$(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() == getDocHeight()) {
           alert("bottom!");
       }
});

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

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