我目前在我的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 - 导航链接(使用虚拟链接)
<a href="link.com/#portfolio>portfolio</a>
HTML - div
<div id="portfolio></div>