我是工作在一个网站,在顶部有一个固定的标题。但是,当我导航到锚时,开始的内容会被标题隐藏。有没有更好的方法来抵消我正在使用的代码。我想这和下面的台词有关。整个剧本都在下面的小提琴上。
$('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);
});
});
发布于 2015-11-27 10:11:05
您可以添加您的scrollPosition
和导航栏的高度(80 it ),这样当导航条底部到达该部分时,它就会发生变化:
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推荐的
您可以做的另一件事是将高度设置为变量,而不是手动将所需的80放置在任何地方。这也将允许你改变导航的高度,而不必回去编辑你的JS。为此:
在加载或调整文档大小时,捕获变量中nav的高度:
$(window).on('load resize', function () {
headerHeight = $('header').height();
});
在任何地方输入变量名"80“都会被放置。
https://stackoverflow.com/questions/33934990
复制