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

新手上路,请多包涵

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

原文由 ThomasReggi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 289
2 个回答

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

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

 $(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");
        });
    }

});

原文由 mrtsherman 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

你应该将卷轴绑定到这个:

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

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

原文由 josetapadas 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题