[英]How to account for the height of a navbar when using a smooth scroll function
I have a smooth scroll function that is used to scroll to specific sections of my page when links are clicked on. 我有一个平滑的滚动功能,当单击链接时,该功能可用于滚动到页面的特定部分。 However, when it automatically scrolls to a section, it does not account for the height of my fixed navbar, which ends up covering up some of the content. 但是,当它自动滚动到某个部分时,它并不能解决我固定的导航栏的高度,该导航栏最终掩盖了某些内容。 I would like to calculate the height of the navbar and subtract it from the scroll position within my current function 我想计算导航栏的高度并将其从当前函数中的滚动位置中减去
$(function() {
$('a[href*="#"]:not(.carousel-control)').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
You need to add the height of your navbar to scrollTop: target.offset().top
. 您需要将导航栏的高度添加到scrollTop: target.offset().top
。 This is an integer value, and can be calculated by simply referencing the .height()
of the navbar DOM element itself. 这是一个整数值,可以通过简单地引用导航栏DOM元素本身的.height()
来计算。
Here's an example assuming a navbar with the class of navbar
: 这是一个示例,假设导航栏的类别为navbar
:
scrollTop: target.offset().top + $('.navbar').height()
Hope this helps! 希望这可以帮助! :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.