【发布时间】:2015-05-11 19:58:35
【问题描述】:
我创建了一个单页垂直滚动。当用户单击“关于”之类的锚点时,它将滚动到该位置。 需要记住的是,我使用高度为 80 像素的固定标题。
以上示例有效。当我用锚点“about”点击“about us”时,它会滚动到id为“about”的部分。没什么特别的。
但问题如下。当我说,我想将访问者导航到单页设计中的一个特殊位置。例如像这样:www.mydomain.com/#about - 当输入上面的 URL 时,它应该直接滚动到那个位置。但这我找不到工作。我不知道如何解释这一点,因为有很多场景发生在我身上。就像它会直接滚动到底部页面,或者它不会滚动到该部分,它会停止到较晚,或者位置不减去导致固定标题与该部分内容重叠的标题。 target 位置减去固定标头很重要。
除此之外,我认为我在某些部分使用了不必要的代码。一些如何改进我的代码的建议也很好。
A working code you can find here
代码:
我的代码的第一部分。这里我控制点击功能。当用户单击#primary-navwrapper 内的链接时,它应该执行该功能。将询问的哈希链接存储在 anchorId 中,并将其设置为 scrollToAnchor 函数。然后它得到该哈希的位置减少了固定的标头(因此标头不会与内容重叠)。并使用当前的 anchorId 更新哈希。
// An offset to push the content down from the top
var offset = $('#header').outerHeight();
// Navigation click action
// Scroll to # HASH ID
$('#primary-navwrapper li a[href^="#"]').click(function(event) {
// Prevent from default action to intitiate
event.preventDefault();
// The id of the section we want to go to
var anchorId = $(this).attr('href');
scrollToAnchor(anchorId);
return false;
});
function scrollToAnchor(anchorId) {
// 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" + target);
// The magic...smooth scrollin' goodness.
$('html, body').animate({ scrollTop: target }, 500, function () {
//window.location.hash = '!' + id;
window.location.hash = anchorId;
});
}
是否有人对此有解决方案或一些建议。 期待您的回答。
卡斯帕
【问题讨论】:
-
在this answer 抢购,可能会有帮助。
标签: javascript jquery css