我想为页面上的 anchor 使用平滑滚动。 因此我使用以下代码:
<script>
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
</script>
唯一的问题是我有一个固定的标题,高度为 88px。因此,当单击 anchor 时,它当前会滚动到很远。
如何扩展我的代码以使其正常工作?
最佳答案
如果您知道您的固定标题始终的高度为 88 像素,您只需将该值添加到最终滚动位置以为其腾出空间:)
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + 88
}, 500);
如果固定标题高度可能会改变,您需要检查它的 outerHeight 并将其添加到偏移量。假设固定 header 的 jQuery 对象存储为 $fixedHeader
:
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + $fixedHeader.outerHeight()
}, 500);
关于javascript - anchor 慢速滚动固定标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45689274/