我试图用JavaScript检测浏览器滚动条的位置,以确定当前视图在页面中的位置。
我的猜测是,我必须检测拇指在轨道上的位置,然后是拇指的高度占轨道总高度的百分比。是我过于复杂了,还是JavaScript提供了一个更简单的解决方案?代码会是什么样子?
我试图用JavaScript检测浏览器滚动条的位置,以确定当前视图在页面中的位置。
我的猜测是,我必须检测拇指在轨道上的位置,然后是拇指的高度占轨道总高度的百分比。是我过于复杂了,还是JavaScript提供了一个更简单的解决方案?代码会是什么样子?
当前回答
这是另一种获取滚动位置的方法:
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
其他回答
2018年的答案:
做到这一点的最好方法是使用交集观察者API。
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. Unfortunately, as the web has matured, the need for this kind of information has grown. Intersection information is needed for many reasons, such as: Lazy-loading of images or other content as a page is scrolled. Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages. Reporting of visibility of advertisements in order to calculate ad revenues. Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result. Implementing intersection detection in the past involved event handlers and loops calling methods like Element.getBoundingClientRect() to build up the needed information for every element affected. Since all this code runs on the main thread, even one of these can cause performance problems. When a site is loaded with these tests, things can get downright ugly.
请看下面的代码示例:
Var选项= { 根:document.querySelector(“# scrollArea”), rootMargin:“0 px”, 阈值:1.0 } var observer = new IntersectionObserver(回调,选项); var target = document.querySelector('#listItem'); observer.observe(目标);
大多数现代浏览器都支持IntersectionObserver,但是为了向后兼容,您应该使用polyfill。
document.getScroll = function() {
if (window.pageYOffset != undefined) {
return [pageXOffset, pageYOffset];
} else {
var sx, sy, d = document,
r = d.documentElement,
b = d.body;
sx = r.scrollLeft || b.scrollLeft || 0;
sy = r.scrollTop || b.scrollTop || 0;
return [sx, sy];
}
}
返回一个包含两个整数的数组- [scrollLeft, scrollTop]
如果你关心整个页面,你可以使用这个:
document.body.getBoundingClientRect().top
片段
窗口接口的只读scrollY属性返回 文档当前垂直滚动的像素数。
窗口。addEventListener(“滚动”,函数(){console.log (this.scrollY)}) html{高度:5000 px}
更短的版本使用匿名箭头函数(ES6)并避免使用此功能
窗口。addEventListener(“scroll”,)=>控制台。 html{高地:5000px}
如果你正在使用jQuery,这里有一个完美的函数:.scrollTop()
doc在这里-> http://api.jquery.com/scrollTop/
注意:你可以使用这个函数来检索或设置位置。
参见:http://api.jquery.com/?s=scroll