最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if a user has scrolled to the bottom in the subpixel precision era - Stack Overflow

programmeradmin1浏览0评论

I've found the classic MDN formula to check if content has been scrolled to the bottom,

element.scrollHeight - element.scrollTop === element.clientHeight

doesn't work for all cases any more. For example, if you change the scale of content to something bigger than 100% for the demo page on MDN you will not get the right result. This happens because now browsers use subpixel precision on elements. Particularly scrollTop for not 100% scale is a fractional value now. Actually the problem happens because of === sign in the formula above.

So what is the simplest, but still reliable, solution?

I've found the classic MDN formula to check if content has been scrolled to the bottom,

element.scrollHeight - element.scrollTop === element.clientHeight

doesn't work for all cases any more. For example, if you change the scale of content to something bigger than 100% for the demo page on MDN you will not get the right result. This happens because now browsers use subpixel precision on elements. Particularly scrollTop for not 100% scale is a fractional value now. Actually the problem happens because of === sign in the formula above.

So what is the simplest, but still reliable, solution?

Share Improve this question edited Apr 13, 2023 at 9:09 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Mar 29, 2019 at 14:37 Konstantin SmolyaninKonstantin Smolyanin 19.2k14 gold badges64 silver badges58 bronze badges 4
  • 1 This also happens on any displays with devicePixelRatio not 1 causing CSS pixels to be scaled, even if the elements themselves are not scaled. – trusktr Commented Feb 11, 2022 at 19:54
  • 2 Does this answer your question? Check if a user has scrolled to the bottom (not just the window, but any element) – TylerH Commented Mar 3, 2023 at 18:38
  • For reference, the answer here by Konstantin (using Math.abs) exists on the canonical) – TylerH Commented Mar 3, 2023 at 18:38
  • ("era" does not appear to be a misspelling of "area". It does appear to refer to time (evolution of web browsers over time).) – Peter Mortensen Commented Apr 13, 2023 at 9:15
Add a ment  | 

2 Answers 2

Reset to default 7

My current solution:

function isContentScrolledToBottom(element) {
    const rest = element.scrollHeight - element.scrollTop;
    return Math.abs(element.clientHeight - rest) < 1;
}

It checks if the element is scrolled to bottom with ±1 accuracy.

This function triggers whenever you scroll, and then you can do something that you want to do.

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

评论列表(0)

  1. 暂无评论