我试图用JavaScript检测浏览器滚动条的位置,以确定当前视图在页面中的位置。

我的猜测是,我必须检测拇指在轨道上的位置,然后是拇指的高度占轨道总高度的百分比。是我过于复杂了,还是JavaScript提供了一个更简单的解决方案?代码会是什么样子?


你可以使用element。scrollTop和元素。scrollLeft分别获取已滚动的垂直和水平偏移量。元素可以是文档。如果你关心整页的话。你可以将它与element进行比较。offsetHeight和element。如果需要百分比,则offsetWidth(同样,element可能是body)。

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]

我这样做的Chrome上的<div>。

元素。scrollTop -由于滚动而隐藏在顶部的像素。如果没有滚动,它的值为0。

元素。scrollHeight -是整个div的像素。

元素。clientHeight -是你在浏览器中看到的像素。

var a = element.scrollTop;

将是位置。

var b = element.scrollHeight - element.clientHeight;

将是scrollTop的最大值。

var c = a / b;

将是滚动的百分比[从0到1]。

如果你正在使用jQuery,这里有一个完美的函数:.scrollTop()

doc在这里-> http://api.jquery.com/scrollTop/

注意:你可以使用这个函数来检索或设置位置。

参见:http://api.jquery.com/?s=scroll

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。

是这样的:)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

这是另一种获取滚动位置的方法:

const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

如果你关心整个页面,你可以使用这个:

document.body.getBoundingClientRect().top

我认为下面的函数可以帮助获得滚动坐标值:

const getScrollCoordinate = (el = window) => ({
  x: el.pageXOffset || el.scrollLeft,
  y: el.pageYOffset || el.scrollTop,
});

我从这个答案中得到了这个想法,只是做了一点改变。

片段

窗口接口的只读scrollY属性返回 文档当前垂直滚动的像素数。

窗口。addEventListener(“滚动”,函数(){console.log (this.scrollY)}) html{高度:5000 px}

更短的版本使用匿名箭头函数(ES6)并避免使用此功能

窗口。addEventListener(“scroll”,)=>控制台。 html{高地:5000px}