如何偏移 scrollTop 以考虑粘性 header 的高度?

How can I offset scrollTop to take into account the height of a sticky header?

我只能糊涂 JS/JQuery,我需要一些帮助来更改下面的这段代码。它用于将页面滚动回相应元素的顶部,但是网站的 header 始终浮动在顶部,因此元素的顶部 x 像素最终位于 [=15= 下方].我该如何编辑它,使其偏移 header(静态数字)的高度?

$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );

如果您的 header 是固定高度,只需在页面顶部 (body) 添加与其高度相等的填充。

CSS:

body { padding-top: {height_of_header}px; }

如果它不是固定高度,那么只需更改 scrollTop,这样您的页面就会滚动到元素的位置 减去 header 的高度:

JS:

$('html, body').animate( { scrollTop: element.offset().top - $('#header').height() }, {duration: 400 } );