admin管理员组文章数量:1289858
In my application, I want to determine the current scroll position, so I have been using this to do so (source: +current+scroll+position+javascript)
window.pageYOffset || document.documentElement.scrollTop
Problem: When I console.log this, it only returns 0 when the page is not positioned and the top.
Question: Is there an alternative way to get the current scroll position?
In my application, I want to determine the current scroll position, so I have been using this to do so (source: https://www.codegrepper./code-examples/javascript/get+current+scroll+position+javascript)
window.pageYOffset || document.documentElement.scrollTop
Problem: When I console.log this, it only returns 0 when the page is not positioned and the top.
Question: Is there an alternative way to get the current scroll position?
Share Improve this question edited Jun 7, 2022 at 18:26 user19251203 asked Jun 7, 2022 at 18:26 user19251203user19251203 3821 gold badge5 silver badges18 bronze badges3 Answers
Reset to default 3Try window.scrollY
.
The read-only scrollY property of the Window interface returns the number of pixels that the document is currently scrolled vertically.
https://developer.mozilla/en-US/docs/Web/API/Window/scrollY
recently i had the same problem. So in order to get the position as a percentage I end up do the following
window.addEventListener("scroll", function() {
const maxHeight = document.body.scrollHeight - window.innerHeight;
console.log((window.pageYOffset * 100) / maxHeight);
});
We subtract window.innerHeight
from document.body.scrollHeight
besause window.pageYOffset
represents the top of the viewport. So in order for window.pageYOffset
to match document.body.scrollHeight
we do the above subtraction.
PS.: The above returns a float number. you can use parseInt(...)
to convert it to integer if you'd like.
const maxHeight = document.documentElement.scrollHeight - window.innerHeight;
In modern web development, it's remended to use the document.documentElement.scrollHeight
property instead of document.body.scrollHeight
when you want to access the total scrollable height of the document, as the former is more reliable and works consistently across browsers.
本文标签: javascriptCorrect way to get Scroll PositionStack Overflow
版权声明:本文标题:javascript - Correct way to get Scroll Position - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741440168a2378867.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论