gpt4 book ai didi

javascript - JQuery - 在加载并直接转到带有 anchor 的 URL 时获取偏移量

转载 作者:搜寻专家 更新时间:2023-11-01 05:29:30 26 4
gpt4 key购买 nike

我尝试添加以下功能:当我输入带有 anchor 的 URL 时,我想直接在 anchor 上。我的问题是我有一个固定的 header ,我当前的 JQuery 代码没有考虑我设置的偏移量( 55 ,即 the height of header )。

这是代码片段:

 if ($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
var hash = this.hash;
$('html,body').animate({ scrollTop: target.offset().top - 55 }, 300, function() {
location.hash = hash;
});
}
}

此代码片段位于 [anchor.js][1] 脚本中。

我很好地重定向到 anchor ,但是无论我采用什么偏移值,最终结果都不会考虑这一点,因此在加载页面后 anchor 名称被固定标题隐藏。

如果有人可以帮我解决这个问题,

提前致谢。

ps:我只想让它在 Firefox 和 Chrome 上运行。

更新

看来解决方案可能来自this link .

为此,我必须在 <a name="..."></a> 之前插入标签 <span>class='direct_anchor' 标记(使用 .before Jquery 函数),所以我在我的 CSS 中包含以下规则:

.direct_anchor {
display: block;
height: 55px; // Height of fixed header
margin-top: -55px;
visibility: hidden;
}

最后,这是我直接在地址栏中输入带有哈希扩展名的 URL 的情况的代码片段:

var target = $('[name="'+location.href.split("#")[1]+'"]');
var hash = location.href.split("#")[1];
if (target.length) {
location.hash = hash;
$('html,body').animate({ scrollTop: target.offset().top - 55 }, 300);
target.before( "<span class='direct_anchor'></span>" );
}

不幸的是,我无法让它工作,class='direct_anchor' CSS 规则似乎未应用于 span标签。

我不是 Jquery 专家,任何人都可以看出哪里出了问题?

感谢您的帮助。

最佳答案

我调试并发现脚本在重新加载时没有在 if 语句中执行。

$(window).bind("load", function () {

$('a[href*="#"]:not([href="#SECTION"]):not([href*="wikipedia"]):not([href*="mjx-eqn"])').click(function(event) {
event.preventDefault();
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) {
var hash = this.hash;
$('html,body').animate({ scrollTop: target.offset().top - 55 }, 300, function() {
href = window.location.href;
history.pushState({page:href}, null, href.split('#')[0]+hash);
});
return false;
}
}
});

$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
var target = window.location.href.split('#');
var href = target[0];
if (state) {
$('html,body').animate({ scrollTop: 0 }, 300, function() {
history.replaceState({}, null, href);
});
}
});

// code changed here
var target = $("[name='"+location.href.split("#")[1]+"']");
if (target.length) {
$('html,body').animate({ scrollTop: target.offset().top-55},300);
}
});

请注意,您可以使用 name 而不是 id 作为选择器来获取元素。这是正在创建的问题,现在已解决。我已经通过调试进行了检查,所以不能确定,但​​它在 chrome 中运行良好。我无法 checkin Firefox,因为我不知道如何使用调试器编辑脚本。

关于javascript - JQuery - 在加载并直接转到带有 anchor 的 URL 时获取偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36394348/

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