Javascript 如何获取和设置当前网页滚动位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4096863/
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 10:35:47  来源:igfitidea点击:

How to get and set the current web page scroll position?

javascripthtml

提问by xyz

How can I get and set the current web page scroll position?

如何获取和设置当前网页滚动位置?

I have a long form which needs to be refreshed based on user actions/input. When this happens, the page resets to the very top, which is annoying to the users, because they have to scroll back down to the point they were at.

我有一个很长的表单,需要根据用户操作/输入进行刷新。发生这种情况时,页面会重置到最顶部,这对用户来说很烦人,因为他们必须向下滚动到他们所在的位置。

If I could capture the current scroll position (in a hidden input) before the page reloads, I could then set it back after it reloads.

如果我可以在页面重新加载之前捕获当前滚动位置(在隐藏输入中),那么我可以在重新加载后将其设置回来。

采纳答案by SLaks

You're looking for the document.documentElement.scrollTopproperty.

您正在寻找该document.documentElement.scrollTop物业。

回答by tobek

The currently accepted answer is incorrect - document.documentElement.scrollTopalways returns 0 on Chrome. This is because WebKit uses bodyfor keeping track of scrolling, whereas Firefox and IE use html.

当前接受的答案不正确 -document.documentElement.scrollTop在 Chrome 上始终返回 0。这是因为 WebKitbody用于跟踪滚动,而 Firefox 和 IE 使用html.

To get the current position, you want:

要获得当前位置,您需要:

document.documentElement.scrollTop || document.body.scrollTop

You can set the current position to 1000px down the page like so:

您可以将当前位置设置为页面下方 1000 像素,如下所示:

document.documentElement.scrollTop = document.body.scrollTop = 1000;

Or, using jQuery (animate it while you're at it!):

或者,使用 jQuery(在您使用它时为其设置动画!):

$("html, body").animate({ scrollTop: "1000px" });

回答by gyo

There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chromeon Macand iOSseems to always return 0when using document.documentElement.scrollTopor jQuery's $(window).scrollTop().

浏览器显示当前窗口滚动坐标的方式存在一些不一致。谷歌浏览器的MaciOS版似乎总是返回0使用时document.documentElement.scrollTop或jQuery的$(window).scrollTop()

However, it works consistently with:

但是,它始终适用于:

// horizontal scrolling amount
window.pageXOffset

// vertical scrolling amount
window.pageYOffset

回答by AXE Labs

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

我使用了 HTML5 本地存储解决方案......我的所有链接都调用了一个函数,该函数在更改 window.location 之前进行设置:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

每个页面在主体的 onLoad 中都有这个:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }