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

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

问题描述

如果你去到一个页面并围绕滚动然后刷新页面将在你离开它当场刷新。这是伟大的,但是这也发生在那里是URL中的锚定位页面。一个例子是,如果你点击一个链接 http://example.com/post/244#comment5 上寻找你身边后刷新页面就不会在锚和页面跳转各地。有什么办法使用JavaScript prevent呢?所以没有实体 - 你总是会浏览到锚。

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.

推荐答案

请注意,这似乎并没有在Chrome中工作了。何塞的答案似乎像目前,最好的解决办法。我要离开这个答案完好,以供参考。

Please note that this does not seem to work in Chrome any more. Jose's answer seems like the current, best solution. I'm leaving this answer intact for reference.

基本上,如果使用锚我们绑定到窗口滚动事件。的想法是,在第一涡旋事件具有属于由浏览器完成的自动重新定位。如果发生这种情况,我们做我们自己的重新定位,然后删除约束的事件。这$ P $从borking系统pvents随后的页面滚动。

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

});

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

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