我正在使用非常标准的平滑滚动javascript链接到我的wordpress网站中相同页面上的锚点,并且工作正常。但是,当尝试在另一页上打开锚点时,链接/按钮没有响应。就像链接/按钮完全失效。如果我右键单击它,然后在新选项卡中选择“打开”,它将很好地工作。如果我从网站标题中删除有问题的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
});
});
此代码似乎假定到锚点的每个链接都将链接到锚点[[在当前页面上。您需要添加代码以检测链接是否转到另一个页面,如果是,则直接在该页面导航(而不是尝试平滑滚动效果到当前页面的锚点)。
将此代码添加到点击处理程序的开头:if ( document.URL.replace(/#.*$/, "") != $(this).attr('href').replace(/#.*$/, "") ) {
// Different URL (not counting the hash)
document.location.href = $(this).attr('href');
return;
}
event.target
的动画,而不是为字符串变量hash
设置动画> var hash = event.target.href;
$('html, body').animate({
scrollTop: $(event.target).offset().top
}, 800, function(){