Offset scroll anchor in HTML with Bootstrap 4 fixed navbar

前端 未结 5 590
孤独总比滥情好
孤独总比滥情好 2020-12-29 06:17

So, I have this single page that consists of a few sections. Users can go to these sections by scrolling themselves or clicking in the navbar (a href with anchor). Due to th

5条回答
  •  清酒与你
    2020-12-29 07:00

    I like to dynamically offset the height header (or navbar) like this:

    $('.nav-link').click(function(e){
        let divCoords = $(e.target.hash).offset();
        let height = $('header').height();
        e.preventDefault();
        window.scrollTo({
        left: divCoords.left, 
        top: divCoords.top - height,
        behavior: 'smooth'
        });
    });
    

提交回复
热议问题