Javascript 防止浏览器在刷新时自动滚动

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

Prevent automatic browser scroll on refresh

javascriptbrowser

提问by ThomasReggi

If you go to a page a and scroll around then refresh the page will refresh at the spot where you left it. This is great, however this also occurs on pages where there is a anchor location in the url. An example would be if you clicked on a link http://example.com/post/244#comment5and refreshed the page after looking around you would not be at the anchor and the page jumps around. Is there any way to prevent this with javascript? So that no-matter-what you would always navigate to the anchor.

如果你转到一个页面 a 并滚动然后刷新页面将在你离开它的地方刷新。这很好,但是这也发生在 url 中有锚位置的页面上。一个例子是,如果你点击一个链接http://example.com/post/244#comment5并在环顾四周后刷新页面,你就不会在锚点处,页面会跳来跳去。有没有办法用javascript防止这种情况?因此,无论您做什么,您都将始终导航到锚点。

采纳答案by mrtsherman

This solution is no longer recommended due to changes in browser behavior. See other answers.

由于浏览器行为的变化,不再推荐此解决方案。查看其他答案。

Basically, if an anchor is used we bind to the windows scroll event. The idea being that the first scroll event has to belong to the automatic repositioning done by the browser. When this occurs we do our own repositioning and then remove the bound event. This prevents subsequent page scrolls from borking the system.

基本上,如果使用锚点,我们将绑定到 windows 滚动事件。这个想法是第一个滚动事件必须属于浏览器完成的自动重新定位。发生这种情况时,我们会自行重新定位,然后移除绑定事件。这可以防止后续页面滚动使系统崩溃。

$(document).ready(function() {
    if (window.location.hash) { 
        //bind to scroll function
        $(document).scroll( function() {
            var hash = window.location.hash
            var hashName = hash.substring(1, hash.length);
            var element;

            //if element has this id then scroll to it
            if ($(hash).length != 0) {
                element = $(hash);
            }
            //catch cases of links that use anchor name
            else if ($('a[name="' + hashName + '"]').length != 0)
            {
                //just use the first one in case there are multiples
                element = $('a[name="' + hashName + '"]:first');
            }

            //if we have a target then go to it
            if (element != undefined) {
                window.scrollTo(0, element.position().top);
            }
            //unbind the scroll event
            $(document).unbind("scroll");
        });
    }

});

回答by josetapadas

On Chrome, even if you force scrollTop to 0 it will jump afterwards after the first scroll event.

在 Chrome 上,即使您将 scrollTop 强制为 0,它也会在第一个滚动事件之后跳转。

You should bind the scroll to this:

你应该将滚动绑定到这个:

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

So the browser is tricked to believe that it was on the beginning before the refresh.

所以浏览器被欺骗相信它是在刷新之前的开始。

回答by imos

To disable automatic scroll restoration just add this tag to head section.

要禁用自动滚动恢复,只需将此标签添加到 head 部分。

<script>history.scrollRestoration = "manual"</script>

It's not supported by IE. Browser compatibility.

IE 不支持。浏览器兼容性。

回答by Janaka Dombawela

After number of failures finally I managed to do the trick. anzois correct here as using beforeunloadwill make the page jump to top when a user reloads the page or clicks a link. So unloadis the clearly way to do this.

经过多次失败,我终于成功了。anzo在这里是正确的,因为使用beforeunload将使页面在用户重新加载页面或单击链接时跳转到顶部。这样unload做的明确方法也是如此。

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

Javascript way(Thanks ProfNandaa):

Javascript 方式(感谢ProfNandaa):

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

EDIT: 16/07/2015

编辑:16/07/2015

The jump issue is still there with Firefox even with unloadevent.

即使有unload事件,Firefox 仍然存在跳转问题。

回答by Oliver Schafeld

Here's a a more general approach. Instead of trying to prevent the browser from scrolling (or jumping to the top as it would look like) I just restore the previous position on the page. I.e. I'm recording the current y-offset of the page in localStorage and scroll to this position once the page has loaded.

这是一种更通用的方法。与其试图阻止浏览器滚动(或像它看起来那样跳到顶部),我只是恢复了页面上的先前位置。即我正在 localStorage 中记录页面的当前 y 偏移量,并在页面加载后滚动到该位置。

function storePagePosition() {
  var page_y = window.pageYOffset;
  localStorage.setItem("page_y", page_y);
}


window.addEventListener("scroll", storePagePosition);


var currentPageY;

try {
  currentPageY = localStorage.getItem("page_y");

  if (currentPageY === undefined) {
    localStorage.setItem("page_y") = 0;
  }

  window.scrollTo( 0, currentPageY );
} catch (e) {
    // no localStorage available
}

回答by Daut

You can just put a # at the end so the page will load at the top.

你可以在末尾加上一个#,这样页面就会在顶部加载。

Works on all browsers, mobile and desktop, because it is so simple.

适用于所有浏览器、移动设备和桌面设备,因为它非常简单。

$(document).ready(function() {
var url = window.location.href;
console.log(url);
if( url.indexOf('#') < 0 ) {
    window.location.replace(url + "#");
} else {
    window.location.replace(url);
}

});

});

// This loads the page with a # at the end.

// 这会以# 结尾加载页面。

回答by Alex Having Fun

This works for me.

这对我有用。

    //Reset scroll top

    history.scrollRestoration = "manual"

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

回答by nikmd23

You should be able to.

你应该能够。

Onload, check if window.location.hashhas a value. If it does, grab the element with an id that matches the hash value. Find the position of the element (recursive calls to offsetTop/offsetLeft) and then pass those values into the window.scrollTo(x, y)method.

Onload,检查是否window.location.hash有值。如果是,则获取具有与哈希值匹配的 id 的元素。找到元素的位置(递归调用 offsetTop/offsetLeft),然后将这些值传递给window.scrollTo(x, y)方法。

This should scroll the page to the desired element.

这应该将页面滚动到所需的元素。