当我访问 my_site.com/page.php#something
时,滚动位置是携带此特定主题标签的元素之一,而不是页面顶部。
执行 window.scrollTo(0, 0);
不会改变这一事实。那还能做什么呢?
编辑:还尝试了 How to disable anchor "jump" when loading a page? 接受的答案。似乎不再起作用了。
最佳答案
您要做的就是存储主题标签以供以后使用,然后将其删除,以便浏览器没有任何内容可滚动。
重要的是,不要将这部分代码放入 $() 或 $(window).load() 函数中,因为这会太晚,并且浏览器已经移至该标记。
// 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 () {});
}
});
关于jquery - 如何在加载页面时禁用 anchor 跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27096621/