Javascript平滑滚动冲突
Javascript smooth scroll conflict
我正在使用非常标准的平滑滚动 javascript 到 link 来锚定我的 wordpress 网站中相同页面上的点,它工作正常。但是,当我尝试在另一个页面上打开锚点时,link/button 没有任何响应。就好像 link/button 完全死了一样。如果我右键单击它并 select 在新选项卡中打开,它工作正常。如果我从站点 header 中删除有问题的 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
});
});
您需要为 event.target
单击的 Dom 元素设置动画,而不是字符串变量 hash
var hash = event.target.href;
$('html, body').animate({
scrollTop: $(event.target).offset().top
}, 800, function(){
此代码似乎假设每个指向锚点的 link 都会指向当前页面 上的锚点 。您需要添加代码来检测 link 是否转到不同的页面,如果是,则直接导航到那里(而不是尝试对当前页面上的锚点进行平滑滚动效果)。
将此代码添加到点击处理程序的开头:
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 到 link 来锚定我的 wordpress 网站中相同页面上的点,它工作正常。但是,当我尝试在另一个页面上打开锚点时,link/button 没有任何响应。就好像 link/button 完全死了一样。如果我右键单击它并 select 在新选项卡中打开,它工作正常。如果我从站点 header 中删除有问题的 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
});
});
您需要为 event.target
单击的 Dom 元素设置动画,而不是字符串变量 hash
var hash = event.target.href;
$('html, body').animate({
scrollTop: $(event.target).offset().top
}, 800, function(){
此代码似乎假设每个指向锚点的 link 都会指向当前页面 上的锚点 。您需要添加代码来检测 link 是否转到不同的页面,如果是,则直接导航到那里(而不是尝试对当前页面上的锚点进行平滑滚动效果)。
将此代码添加到点击处理程序的开头:
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;
}