gpt4 book ai didi

Javascript平滑滚动冲突

转载 作者:行者123 更新时间:2023-12-04 10:03:33 24 4
gpt4 key购买 nike

我正在使用非常标准的平滑滚动 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com