Javascript 如何使用Javascript获取滚动条位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2481350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:33:07  来源:igfitidea点击:

How to get scrollbar position with Javascript?

javascriptbrowserscrolldom-events

提问by Paul

I'm trying to detect the position of the browser's scrollbar with JavaScript to decide where in the page the current view is. My guess is that I have to detect where the thumb on the track is, and then the height of the thumb as a percentage of the total height of the track. Am I over-complicating it, or does JavaScript offer an easier solution than that? Any ideas code-wise?

我试图用 JavaScript 检测浏览器滚动条的位置,以确定当前视图在页面中的位置。我的猜测是我必须检测轨道上拇指的位置,然后拇指的高度占轨道总高度的百分比。我是否过于复杂了,还是 JavaScript 提供了比这更简单的解决方案?任何想法代码明智?

回答by Max Shawabkeh

You can use element.scrollTopand element.scrollLeftto get the vertical and horizontal offset, respectively, that has been scrolled. elementcan be document.bodyif you care about the whole page. You can compare it to element.offsetHeightand element.offsetWidth(again, elementmay be the body) if you need percentages.

您可以使用element.scrollTopelement.scrollLeft分别获取已滚动的垂直和水平偏移量。elementdocument.body如果你关心整个页面。如果您需要百分比,您可以将它与element.offsetHeightelement.offsetWidth(同样,element可能是身体)进行比较。

回答by Gatsby

I did this for a <div>on Chrome.

<div>在 Chrome 上做了这个。

element.scrollTop- is the pixels hidden in top due to the scroll. With no scroll its value is 0.

element .scrollTop- 由于滚动而隐藏在顶部的像素。没有滚动它的值为 0。

element.scrollHeight- is the pixels of the whole div.

element .scrollHeight- 是整个 div 的像素。

element.clientHeight- is the pixels that you see in your browser.

element .clientHeight- 是您在浏览器中看到的像素。

var a = element.scrollTop;

will be the position.

将是位置。

var b = element.scrollHeight - element.clientHeight;

will be the maximumvalue for scrollTop.

将是最大的价值scrollTop的

var c = a / b;

will be the percent of scroll [from 0 to 1].

将是滚动的百分比[from 0 to 1]

回答by kennebec

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];
    }
}

returns an array with two integers- [scrollLeft, scrollTop]

返回一个包含两个整数的数组 - [scrollLeft, scrollTop]

回答by Brayan Pastor

it's like this :)

就像这样 :)

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

回答by str

Answer for 2018:

2018 年的答案

The best way to do things like that is to use the Intersection Observer API.

执行此类操作的最佳方法是使用Intersection Observer 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.

Intersection Observer API 提供了一种异步观察目标元素与祖先元素或顶级文档视口的交集变化的方法。

从历史上看,检测一个元素的可见性或两个元素相互之间的相对可见性一直是一项艰巨的任务,解决方案不可靠并且容易导致浏览器和用户访问的站点变得缓慢。不幸的是,随着网络的成熟,对此类信息的需求也在增长。需要交点信息的原因有很多,例如:

  • 在页面滚动时延迟加载图像或其他内容。
  • 实现“无限滚动”网站,在您滚动时加载和呈现越来越多的内容,这样用户就不必翻阅页面。
  • 报告广告的可见性以计算广告收入。
  • 根据用户是否会看到结果来决定是否执行任务或动画处理。

过去实现交叉检测涉及事件处理程序和循环调用方法,如 Element.getBoundingClientRect() 为每个受影响的元素构建所需的信息。由于所有这些代码都在主线程上运行,即使其中之一也会导致性能问题。当一个站点加载了这些测试时,事情会变得非常丑陋。

See the following code example:

请参阅以下代码示例:

var options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

var target = document.querySelector('#listItem');
observer.observe(target);
var options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

var target = document.querySelector('#listItem');
observer.observe(target);

Most modern browsers support the IntersectionObserver, but you should use the polyfillfor backward-compatibility.

大多数现代浏览器都支持 IntersectionObserver,但为了向后兼容,您应该使用polyfill

回答by lemospy

if you care for the whole page. you can use this:

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

document.body.getBoundingClientRect().top

回答by Gor

Here is the other way to get scroll position

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

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

回答by Simon the Salmon

If you are using jQuery there is a perfect function for you: .scrollTop()

如果您正在使用 jQuery,那么有一个完美的函数适合您:.scrollTop()

doc here -> http://api.jquery.com/scrollTop/

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

note: you can use this function to retrieve OR set the position.

注意:您可以使用此功能检索或设置位置。

see also: http://api.jquery.com/?s=scroll

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

回答by AmerllicA

I think the following function can help to have scroll coordinate values:

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

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

I got this idea from this answerwith a little change.

我从这个答案中得到了这个想法,稍作改动。