加载新页面后平滑滚动到锚点

我想导航到新页面上的锚点,但我希望页面在顶部加载,然后立即平滑滚动到相关的锚点。 可以这样做吗?

我是一个完整的新手用Javascript。

这是我目前用于在当前页面内平滑滚动的js。 我只是在链接上应用了一类“滚动”。

非常感谢!

 $(function(){ $('.scroll').on('click',function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top + 'px' }, 1000, 'swing'); }); });  

随着浏览器自动检测hash并带你到那个位置……
我发现你可以先将滚动位置重置为0 ,然后进行平滑滚动。

就像是…

 // to top right away if ( window.location.hash ) scroll(0,0); // void some browsers issue setTimeout( function() { scroll(0,0); }, 1); $(function() { // your current click function $('.scroll').on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top + 'px' }, 1000, 'swing'); }); // *only* if we have anchor on the url if(window.location.hash) { // smooth scroll to the anchor id $('html, body').animate({ scrollTop: $(window.location.hash).offset().top + 'px' }, 1000, 'swing'); } }); 

编辑 :将scroll(0,0)移到$(function(){...}); 防止闪烁。
此外,还添加了带有工作示例的Snippet。
在全屏查看时,效果最佳

  html, body { margin: 0; padding: 0; } .hidden-code { display: none; visibility: hidden; opacity: 0; } .header { background-color: #ccc; padding: 5px; } .header li { padding: 5px; margin: 5px; display: inline-block; } .articles > div { border: 1px solid; margin: 10px; padding: 250px 50px; background-color: #ccc; } div:before { content: attr(id); } .footer { text-align: center; }