Javascript 重新加载浏览器不会将页面重置为顶部

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

Reload browser does not reset page to top

javascriptjqueryaccordionjquery-ui-accordion

提问by imakeitpretty

I thought when you clicked refresh, that the browser was supposed to reset your page to the top? I am using a jsaccordion and when I refresh, it closes the accordion but does not reposition the page to the top.

我以为当您单击刷新时,浏览器应该将您的页面重置到顶部?我正在使用js手风琴,当我刷新时,它会关闭手风琴但不会将页面重新定位到顶部。

http://imip.rvadv.com/index3.html

http://imip.rvadv.com/index3.html

回答by Nikhil Nanjappa

Try this if none of the above worked. This will trick the browser to think it was at the top of the document before refresh.

如果以上都不起作用,请尝试此操作。这将欺骗浏览器在刷新之前认为它位于文档的顶部。

$(window).on('beforeunload', function() {
   $(window).scrollTop(0);
});

回答by Nikola Anusev

Well, as you can see, it does not :)

好吧,正如你所看到的,它没有:)

But you can force it with some simple jQuery:

但是你可以用一些简单的 jQuery 来强制它:

$(document).ready(function(){
    $(this).scrollTop(0);
});

EDIT:

编辑:

The only way that seems to work in IE 9, FF 12 and Chrome 20.0 is the following:

似乎适用于 IE 9、FF 12 和 Chrome 20.0 的唯一方法如下:

$(document).ready(function(){
    $('html').animate({scrollTop:0}, 1);
    $('body').animate({scrollTop:0}, 1);
});

Strange thing is that when I tried scrolling the elements directly without applying any animation (that is, $('html').scrollTop(0)), it didn't work. Since the duration is set to 1 millisecond, the user will not notice anything.

奇怪的是,当我尝试直接滚动元素而不应用任何动画(即$('html').scrollTop(0))时,它不起作用。由于持续时间设置为 1 毫秒,因此用户不会注意到任何事情。

I would be glad if anyone could shed some light on this - why does the scrolling only work with animations?

如果有人能对此有所了解,我会很高兴 - 为什么滚动仅适用于动画?

回答by Niet the Dark Absol

The browser will scroll down to where you were before the reload, as an attempt at convenience. It's only really useful for excessively long pages.

为方便起见,浏览器将向下滚动到重新加载之前的位置。它只对过长的页面真正有用。

You can "fix" this like so:

你可以像这样“修复”这个:

window.onload = function() {document.body.scrollTop = document.documentElement.scrollTop = 0;};

回答by user1680948

Based on last comment by comonpyke and own tests I recommend

基于 comonpyke 的最后评论和我推荐的自己的测试

$(document).ready(function(){
    $('html, body').scrollTop(0);

    $(window).on('load', function() {
    setTimeout(function(){
        $('html, body').scrollTop(0);
    }, 0);
 });
});
  • First scrollTop scrolls early
    • after document ready
  • Second scrollTop scrolls late
    • after load event
      • and after timeout
  • 第一个 scrollTop 提前滚动
    • 文件准备好后
  • 第二个 scrollTop 滚动晚了
    • 加载事件后
      • 和超时后