简体   繁体   English

强制页面在重新加载时返回顶部-Javascript

[英]Force Page to Return to top on Reload - Javascript

I have a problem in vanilla JS that has been asked in slightly differing forms on this site, but there doesn't seem to be an answer for vanilla javascript? 我在香草JS中遇到了一个问题,该问题在本网站上以略有不同的形式被提出,但是香草javascript似乎没有答案? I would like the page to appear at the top on reload / refresh using vanilla JS (without any scrolling back up to the top with scrollTop()). 我希望页面在使用香草JS进行重新加载/刷新时显示在顶部(没有使用scrollTop()滚动回到顶部)。

I've checked these questions and the related answers: 我检查了这些问题和相关的答案:

Prevent automatic browser scroll on refresh 防止浏览器在刷新时自动滚动

Force page scroll position to top at page refresh in HTML 在HTML中刷新页面时强制页面滚动到顶部

Prevent automatic browser scroll on refresh 防止浏览器在刷新时自动滚动

The problem is there are two vanilla JS answers scattered in these questions, one of which doesn't work in IE/Edge, the other one doesn't work in Safari 问题是在这些问题中有两个普通的JS答案,其中一个在IE / Edge中不起作用,另一个在Safari中不起作用

Doesn't work in Safari: 在Safari中不起作用:

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

Doesn't working in IE / Edge 在IE / Edge中不起作用

history.scrollRestoration = "manual";

Surely there must a way of getting a page to appear at the top on refresh / reload? 当然,必须有一种使页面在刷新/重新加载时显示在顶部的方法吗?

Also I can't have it scroll up to the top on reload / refresh so any scrollTop() related answers aren't applicable. 我也不能让它在重新加载/刷新时向上滚动到顶部,因此任何与scrollTop()相关的答案都不适用。

Many thanks in advance 提前谢谢了

You can always just add some flags to include both solutions: 您始终可以仅添加一些标志以包括这两种解决方案:

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

and

if(history && history.scrollRestoration) history.scrollRestoration = "manual";

Also I can't have it scroll up to the top on reload / refresh so any scrollTop() related answers aren't applicable. 我也不能让它在重新加载/刷新时向上滚动到顶部,因此任何与scrollTop()相关的答案都不适用。

also why? 还为什么呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM