如何在加载页面时禁用锚点跳转

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

执行window.scrollTo(0, 0); 不改变这个事实。 什么可以呢?

编辑:还尝试了如何在加载页面时禁用锚点“跳转”的接受答案? 。 似乎不再起作用了。

您需要做的是存储主题标签以供以后使用,然后将其删除,以便浏览器无需滚动到任何内容。

重要的是你不要把这部分代码放在$()或$(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 () {}); } }); 

拥有此HTML代码:

 link 

您可以避免滚动到div元素,而是使用以下代码滚动到窗口的顶部:

 $("a").on("click", function(e) { e.preventDefault(); window.scrollTo(0, 0); }); 

编辑:

你可以尝试添加这个:

 var firstVisit = true; $(window).scroll(function() { if (firstVisit) { window.scrollTo(0, 0); firstVisit = false; } });