gpt4 book ai didi

javascript - 从其他页面单击时 anchor 链接的滚动顶部偏移不起作用

转载 作者:行者123 更新时间:2023-11-28 05:57:39 25 4
gpt4 key购买 nike

我的网站上有一个固定位置的标题,当用户向下滚动时,标题会粘在屏幕顶部。该网站的导航包括两个 anchor 链接,它们向下滚动到主页上的相应部分,然后一个链接到另一页面(博客)。这是我用于平滑滚动 anchor 链接的代码:

$(function() {
$('a[href*="#"]:not([href="#"])').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) {
$('html, body').animate({
scrollTop: target.offset().top - $('header').height()
}, 600);
return false;
}
}
});
});

主页上的一切都运行良好。我遇到的问题是当您在博客页面上单击主页的两个 anchor 链接之一时。从技术上讲,它会出现在主页上应该出现的位置,只不过它不会像您已经在主页上时那样按标题高度偏移位置。

我根本不擅长 JavaScript。我在网上找到了这段代码(并在该网站上获得了一些有关偏移的帮助)。我真的很努力,但还没有成功。为什么会发生这种情况以及如何解决它?

最佳答案

您的问题是您的代码仅适用于点击事件。因此,当您加载网址中带有 anchor 的页面时,不会触发滚动到事件。

您需要一段额外的代码,仅在页面加载时触发。

$(document).ready(function() { 
var elem = $('#_' + window.location.hash.replace('#', ''));
if (elem) {
$.scrollTo(elem.left, elem.top);
}
});

关于javascript - 从其他页面单击时 anchor 链接的滚动顶部偏移不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37517373/

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