Vanilla JavaScript:滚动到页面顶部

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

Vanilla JavaScript: Scroll to Top of Page

javascriptscrolltop

提问by Manngo

I may have missed something, but I cannot get window.scrollTo(0,0)to move to the top of the page.

我可能错过了一些东西,但我无法window.scrollTo(0,0)移动到页面顶部。

I am implementing a sticky asidewhich works well enough. It uses .getBoundingClientRect()to get the initial position.

我正在实施一个aside效果很好的粘性。它用于.getBoundingClientRect()获取初始位置。

However, if the page is partly scrolled, and I refresh the page, it reads the position wrongly, and is positioned in the wrong place.

但是,如果页面部分滚动,并且我刷新页面,则会错误地读取位置,并且定位在错误的位置。

I though I would fix this by executing window.scrollTo(0,0)at the beginning, so that the page is at the top, and the asideis in the right position.

我虽然我会通过window.scrollTo(0,0)在开始时执行来解决这个问题,以便页面位于顶部,并且aside位于正确的位置。

When I run the code, window.scrollTo(0,0)doesn't seem to make any difference.

当我运行代码时,window.scrollTo(0,0)似乎没有任何区别。

What is the correct way to get the reloaded window to start at the top?

让重新加载的窗口从顶部开始的正确方法是什么?

I have tested it on Firefox on the Mac. Chrome and Safari gives a similar behaviour.

我已经在 Mac 上的 Firefox 上对其进行了测试。Chrome 和 Safari 提供了类似的行为。

Please, no jQuery.

请不要使用jQuery。

回答by TKoL

Have you tried waiting for page load before scrollTo? Try using window.onload

您是否尝试过在 scrollTo 之前等待页面加载?尝试使用 window.onload

window.onload = function(){
    window.scrollTo(0,0);
}

回答by TanvirChowdhury

Going to top of the page with a scroll effect is a bit more easier in javascript now with:

使用滚动效果转到页面顶部现在在 javascript 中更容易一些:

https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});

CAUTION

警告

I just checked the mozilla doc right now while updating my answer and I believe it has been updated. Right now the method is window.scroll(x-coord, y-coord) and does not mention or show examples that use the object parameter where you can set the behavior to smooth. I just tried the code and it still works in chrome and firefox and the object parameter is still in the spec.

我刚刚在更新我的答案时检查了 mozilla 文档,我相信它已经更新。现在该方法是 window.scroll(x-coord, y-coord) 并且没有提及或显示使用 object 参数的示例,您可以在其中将行为设置为平滑。我刚刚尝试了代码,它仍然可以在 chrome 和 firefox 中工作,并且对象参数仍在规范中。

Or in Vanilla you can use window.onload event with scrollTo(x,y) function

或者在 Vanilla 中,您可以使用带有 scrollTo(x,y) 函数的 window.onload 事件

window.onload = function(){
    window.scrollTo(0,0);
}