[英]Anchor slow scroll fixed header
我想为页面上的锚点使用平滑滚动。 因此我使用以下代码:
<script>
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
</script>
唯一的问题是我有一个固定的标题,高度为 88px。 所以当点击锚点时,它当前滚动到很远。
如何扩展我的代码以使其正常工作?
如果您知道固定标题的高度始终为 88 像素,则只需将该值添加到最终滚动位置即可为该位置腾出空间:)
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + 88
}, 500);
如果固定标题高度可能会改变,您将需要检查它的外层高度并将其添加到偏移量中。 假设固定标头的 jQuery 对象存储为$fixedHeader
:
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + $fixedHeader.outerHeight()
}, 500);
您是否尝试将 88px 添加到 scrollTop ?
<script>
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + 88;
}, 500);
});
</script>
仅 CSS 解决方案
html{
scroll-behavior: smooth;
}
[id] { scroll-margin-top: 88px }
此 css 将滚动行为设置为平滑,并将页面上的所有锚点设置为具有 scroll-margin-top 属性,该属性将滚动捕捉到设置的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.