小编典典

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

javascript

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


阅读 426

收藏
2020-05-01

共1个答案

小编典典

由于浏览器行为的更改,不再建议使用此解决方案。查看其他答案。

基本上,如果使用锚,则将绑定到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");
        });
    }

});
2020-05-01