防止锚点在页面加载时跳跃

我正在我的wordpress页面上使用’平滑滚动’,我试图让页面顺利滚动到来自外部链接的请求部分(使用锚点( #portfolio )从那里我希望页面开始在顶部,然后滚动到投资组合部分。

发生的事情是它会短暂显示“投资组合部分”(锚点跳转),然后重置到顶部并向下滚动。

 $(function() { $('.menu li a').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $root.animate({ scrollTop: target.offset().top - 75 }, 800, 'swing'); return false; } } }); }); 

页面加载

 $(window).on("load", function() { if (location.hash) { // do the test straight away window.scrollTo(0, 0); // execute it straight away setTimeout(function() { window.scrollTo(0, 0); // run it a bit later also for browser compatibility }, 1); } var urlHash = window.location.href.split("#")[1]; if (urlHash && $('#' + urlHash).length) $('html,body').animate({ scrollTop: $('#' + urlHash).offset().top - 75 }, 800, 'swing'); }); 

如何防止页面加载时出现的“跳跃”?

HTML – 导航链接(使用虚拟链接)

 portfolio 

HTML – div

 

您可以通过更改锚点来绕过浏览器行为,以便它携带一些对页面访问唯一的附加文本。 在下面的示例中,我已将前六行添加到函数中以设置AnchorSeed变量,然后我在您分配urlHash变量的地方使用了该变量:

 $(window).on("load", function() { var AnchorSeed = new Date() * 1; $( ".AnchorUpdate" ).each( function() { $( this ).attr( "id", this.id + AnchorSeed ); } ); if (location.hash) { // do the test straight away window.scrollTo(0, 0); // execute it straight away setTimeout(function() { window.scrollTo(0, 0); // run it a bit later also for browser compatibility }, 1); } var urlHash = window.location.href.split("#")[1] + AnchorSeed; if (urlHash && $('#' + urlHash).length) $('html,body').animate({ scrollTop: $('#' + urlHash).offset().top - 75 }, 800, 'swing'); }); 

并且您需要将AnchorUpdate类添加到您可能跳转到的任何页面元素,以便jQuery例程可以找到它并使用AnchorSeed值更新其id。 在这种情况下,我们知道“投资组合”就是这样一个环节,所以它将被修改为:

 
Jump to Internal Link

您可以给它一个不同的类,表明它需要更新:

 Jump to Internal Link 

然后使用jQuery触发对该类的类似修改:

 $( ".InternalLinkUpdate" ).each( function() { $( this ).attr( "href", $( this ).attr( "href" ) + AnchorSeed ); } ); 

(由于我目前无法从工作代码中复制,我可能会在上面发出标点符号错误 – 但是不应该花太多时间来修改它以使其正常工作。