加载页面时如何禁用锚点跳转 [英] How to disable anchor jump when loading a page

查看:161
本文介绍了加载页面时如何禁用锚点跳转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我访问my_site.com/page.php#something时,滚动位置是带有此特定#标签的元素之一,而不是页面的顶部.

When I visit my_site.com/page.php#something, the scroll position is the one of the element carrying this particular hashtag rather than the top of the page.

执行window.scrollTo(0, 0);不会更改此事实.那能做什么呢?

Executing window.scrollTo(0, 0); doesn't change this fact. What can then?

还尝试了如何禁用锚点的已接受答案.跳"加载页面时?.似乎不再起作用了.

also tried accepted answer from How to disable anchor "jump" when loading a page?. Doesn't seem to work anymore.

推荐答案

您要做的是存储#号标签以供以后使用,然后将其删除,以使浏览器没有任何滚动的对象.

What you have to do is store the hashtag for later use and then delete it so that the browser doesn't have anything to scroll to.

重要的是,不要将那部分代码放在$()或$(window).load()函数中,因为这可能要等到很晚并且浏览器已经移到了标记上.

It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be to late and the browser already have moved to the tag.

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).load(function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});

这篇关于加载页面时如何禁用锚点跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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