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

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

问题描述

当我访问 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?

还尝试了来自 How to disable anchor "跳"加载页面时?.好像不能用了.

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天全站免登陆