参考https://codepen.io/pikeshmn/pen/mMxEdZ
方法:我们使用document.getElementById('header').offsetHeight获取固定导航的高度,
并将滚动偏移到这个值。
var jump=function(e){
e.preventDefault(); //prevent "hard" jump
var target = $(this).attr("href"); //get the target
//perform animated scrolling
$('html,body').animate(
{
scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5 //get top-position of target-element and set it as scroll target
},1000,function() //scrolldelay: 1 seconds
{
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
}
$(document).ready(function()
{
$('a[href*="#"]').bind("click", jump); //get all hrefs
return false;
});
PS:
- 它包括标题和目标之间的 5 像素差异
- 滚动效果不硬,比较流畅;平滑滚动