简体   繁体   中英

Scroll to div with a sticky navigation bar

The page has a sticky navbar that stay on screen all the time. When I am scrolling to the next section( div ) of the page, it will scroll so the div starts at the top of the screen , so the navigation bar cover it a little bit.

How to minus from y scrolling position the navigation bar height ?

    $('html, body').animate({
    scrollTop: $("#section2").offset().top // minus the nav height
}, 1000);

Also - how to make this navbar height available to my javascript (from the css) using a good practice ? (global var?)

You can select your navigation bar (here I gave my navigation bar the id nav ) and get its height by doing:

$("#nav").height();

You can then subtract this from the scrollTop property.

However, do note, if your nav bar has padding and/or a margin, to correctly calculate the height you will need to use a different method from .height . See this answer if you're having difficulties.

See working example below:

 $('html, body').animate({ scrollTop: $("#section2").offset().top - $("#nav").height() // minus the nav height }, 1000); 
 body { margin: 0; } nav { background: black; height: 10vh; width: 100%; position: fixed; } section { height: 100vh; } #section1 { background: red; } #section2 { background: lime; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav id="nav"></nav> <section id="section1">Top</section> <section id="section2">Top</section> 

To know the height of any element :

Go to the Inspector (Ctrl+Shift+i), select the 'nav' element and on the right side, click the box-model. This will give you the height and width of the selected element.

In JavaScript, to get the height :

$("nav").height();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM