【发布时间】:2025-12-15 14:20:12
【问题描述】:
我想知道如何在滚动到另一个部分时更改 URL 栏中的哈希值。我使用以下代码更改视口中可见部分的菜单项类:
函数 setActiveListElements(事件){ // 获取窗口距离页面顶部的偏移量 var windowPos = $(window).scrollTop();
$('#primary-navwrapper li a[href^="#"]').each(function() {
var anchorId = $(this);
var target = $(anchorId.attr("href"));
//console.log(target);
var offsetTop = target.position().top - offset;
if (target.length > 0) {
if (target.position().top - offset <= windowPos && (target.position().top + target.height() + offset ) > windowPos) {
$('#primary-navwrapper li a').removeClass("current");
anchorId.addClass("current");
}
}
});
}
我已经使用了一个代码来更新哈希,当用户点击一个菜单项,但不知道如何将它集成到上面的代码中:
$('#primary-navwrapper li, .list-of-links li').find('a[href^="#"]').click(function(event) { // 防止默认动作启动 event.preventDefault();
$('#primary-navwrapper li a').removeClass("current");
$(this).addClass("current");
var anchorId = $(this).attr("href");
var target = $(anchorId).offset().top - offset;
//console.log(target);
$('html, body').animate({ scrollTop: target }, 500, function () {
window.location.hash = anchorId;
});
});
在上面我使用的代码中:window.location.hash = anchorId;
【问题讨论】: