防止自动浏览器滚动刷新

ThomasReggi提出了一个问题:Prevent automatic browser scroll on refresh,或许与您遇到的问题类似。

回答者mrtsherman给出了该问题的处理方式:

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.

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

});

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:我怎么能把“&”(&)字符通过Ajax吗?
下一篇:如何在添加数据时自动滚动到div的结尾?[重复]

相关推荐

官方社区

扫码加入 JavaScript 社区