简体   繁体   English

使用粘性导航栏滚动到div

[英]Scroll to div with a sticky navigation bar

The page has a sticky navbar that stay on screen all the time. 该页面具有粘性navbar ,该navbar始终保持在屏幕上。 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. 当我滚动到页面的下一部分( div )时,它将滚动,因此div从屏幕顶部开始,因此导航栏稍微覆盖了它。

How to minus from y scrolling position the navigation bar height ? 如何从y滚动位置减去导航栏高度?

    $('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 ? 还-如何通过一种良好的做法使此navbar height可用于我的javascript(来自css)? (global var?) (全局变量?)

You can select your navigation bar (here I gave my navigation bar the id nav ) and get its height by doing: 您可以选择导航栏(在这里,我为导航栏指定了id nav )并通过执行以下操作获取其高度:

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

You can then subtract this from the scrollTop property. 然后可以从scrollTop属性中减去此值。

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 . 但是,请注意,如果导航栏具有填充和/或边距,则要正确计算高度,您将需要使用与.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. 转到检查器(Ctrl + Shift + i),选择“ nav”元素,然后在右侧单击框模型。 This will give you the height and width of the selected element. 这将为您提供所选元素的高度和宽度。

In JavaScript, to get the height : 在JavaScript中,获取高度:

$("nav").height();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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