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

查看:18
本文介绍了防止浏览器在刷新时自动滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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#comment5 and 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.

推荐答案

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

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

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

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.

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

});

这篇关于防止浏览器在刷新时自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆