Cas*_*ert 2 javascript css jquery
我创建了一个单页垂直滚动。当用户单击“关于”等锚点时,它将滚动到该位置。需要记住的是,我使用高度为 80 像素的固定标题。
上面的例子有效。当我点击锚点为“about”的“关于我们”时,它将滚动到 id 为“about”的部分。没什么特别的。
但问题如下。当我说的时候,我想将访问者引导到一页设计中的一个特殊位置。例如:www.mydomain.com/#about - 当输入上面的 URL 时,它应该直接滚动到该位置。但这我找不到工作。我不知道如何解释这一点,因为有很多场景发生在我身上。就像它会直接滚动到底部页面,或者滚动不特定于该部分,它停止到很晚,或者位置不减去导致固定标题与该部分的内容重叠的标题。重要的是该target位置减去固定标头。
除此之外,我认为我在某些部分使用了不必要的代码。一些如何改进我的代码的建议也很好。
代码:我的代码的第一部分。这里我控制点击功能。当用户单击其中的链接时,#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;
});
}
Run Code Online (Sandbox Code Playgroud)
有人有解决方案吗?或者可能有一些建议。留意你的答案。
卡斯帕
小智 5
这对我有用。
html {
scroll-padding-top: 70px; /* height of sticky header */
}
Run Code Online (Sandbox Code Playgroud)