【发布时间】:2015-05-09 17:01:45
【问题描述】:
有一段时间,我正在尝试编写一个不错的单页导航,滚动到右侧锚部分并更新他在菜单中的当前状态。
那么我需要哪种功能? - 处理点击事件的函数:当用户点击锚链接时,它应该滚动到该部分并更新菜单的当前状态。
- 在滚动时摆脱活动状态的函数。
除此之外,我使用了一个固定的标题。所以标题的高度应该减去滚动位置,以避免粘性标题重叠内容。
想出了这个:
// An offset to push the content down from the top
var offset = $('#header').outerHeight();
$('#primary-navwrapper').find('li a[href^="#"]').click(function(event) {
// Current class switch
$(this).removeClass("current");
$(this).addClass("current");
// The id of the section we want to go to.
var anchorId = $(this).attr("href");
// Our scroll target : the top position of
// the section that has the id referenced by our href.
var target = $(anchorId).offset().top - offset;
//console.log(target);
$('html, body').animate({ scrollTop: target }, 500, function () {
window.location.hash = anchorId;
});
// Prevent from default action to intitiate
event.preventDefault();
return false;
});
function setActiveListElements(event) {
// Get the offset of the window from the top of page
var windowPos = $(window).scrollTop();
$('nav li a[href^="#"]').each(function() {
var currentId = $(this);
console.log(this);
// if for active
var target = currentId.attr("href");
console.log(target);
var offsetTop = target.position().top - offset;
//var offsetBottom = offsetTop + target.height();
if (target.length > 0) {
console.log(target.position().top + target.height());
if (target.position().top - offset <= windowPos && target.position().top + target.height() > windowPos) {
$('#primary-navwrapper li a').removeClass("current");
$(this).addClass("current");
}
}
});
}
它将滚动到它的位置,但不会更新当前状态。除此之外,我还尝试在滚动时更新 URL 中的哈希值,但不知道应该如何完成。
如果这可以更短和更好的编码,我也不反对,所以欢迎提出建议:)
【问题讨论】:
-
你可以使用(我试图......但我得到错误......)而不是(我想要......)..之后我认为你会得到帮助..你的问题的答案很简单..但它只需要时间..祝你好运
-
您考虑过使用fullPage.js 吗?