已修复 Header 隐藏内容顶部
Fixed Header Hiding Top of Content
我在一个顶部有固定 header 的网站上工作。但是,当我导航到锚点时,开始的内容被 header 隐藏了。有没有更好的方法来抵消我正在使用的代码。我认为这与下面的几行有关。整个脚本在下面fiddle
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
您可以添加 scrollPosition
和导航栏的高度 (80px),以便在导航底部到达该部分时发生变化:
if (refElement.position().top <= scrollPosition + 80 && refElement.position().top + refElement.height() > scrollPosition + 80 )
并滚动到部分。减去导航栏的高度:
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 80
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
缓存高度 - 根据 Joseph Marikle 的建议
您可以做的另一件事是将高度设置为可变,而不是手动将 80 放在需要的地方。这也将允许您更改导航的高度,而无需返回并编辑您的 JS。为此:
在加载文档或调整文档大小时在变量中捕捉导航的高度:
$(window).on('load resize', function () {
headerHeight = $('header').height();
});
并在本应放置“80”的任何地方输入该变量名。
我在一个顶部有固定 header 的网站上工作。但是,当我导航到锚点时,开始的内容被 header 隐藏了。有没有更好的方法来抵消我正在使用的代码。我认为这与下面的几行有关。整个脚本在下面fiddle
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
您可以添加 scrollPosition
和导航栏的高度 (80px),以便在导航底部到达该部分时发生变化:
if (refElement.position().top <= scrollPosition + 80 && refElement.position().top + refElement.height() > scrollPosition + 80 )
并滚动到部分。减去导航栏的高度:
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 80
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
缓存高度 - 根据 Joseph Marikle 的建议
您可以做的另一件事是将高度设置为可变,而不是手动将 80 放在需要的地方。这也将允许您更改导航的高度,而无需返回并编辑您的 JS。为此:
在加载文档或调整文档大小时在变量中捕捉导航的高度:
$(window).on('load resize', function () {
headerHeight = $('header').height();
});
并在本应放置“80”的任何地方输入该变量名。