我正在使用相当标准的平滑滚动 javascript 链接到我的 WordPress 网站中同一页面上的 anchor ,它工作得很好。但是,当我尝试打开另一个页面上的 anchor 时,我没有收到链接/按钮的响应。就像链接/按钮完全失效了一样。如果我右键单击它并选择在新选项卡中打开,它就可以正常工作。如果我从站点标题中删除有问题的 javascript,它也会起作用。有人能指出冲突可能出在哪里吗?对于那些可能不熟悉的人来说,这是有问题的代码:
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
最佳答案
这段代码似乎假设每个指向 anchor 的链接都将指向当前页面上的 anchor 。您需要添加代码来检测链接是否会转到不同的页面,如果是,则直接导航到那里(而不是尝试对当前页面上的 anchor 进行平滑滚动效果)。
将此代码添加到点击处理程序的开头:
if ( document.URL.replace(/#.*$/, "") != $(this).attr('href').replace(/#.*$/, "") ) {
// Link goes to a different URL than the current page (not counting the hash)
document.location.href = $(this).attr('href');
return;
}
关于Javascript平滑滚动冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61706446/