![](/img/trans.png)
[英]How to change offset on smooth scroll JQuery animation by a height of the navbar
[英]How to account for the height of a navbar when using a smooth scroll 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;
}
}
});
});
您需要将导航栏的高度添加到scrollTop: target.offset().top
。 这是一个整数值,可以通过简单地引用导航栏DOM元素本身的.height()
来计算。
这是一个示例,假设导航栏的类别为navbar
:
scrollTop: target.offset().top + $('.navbar').height()
希望这可以帮助! :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.