简体   繁体   English

滚动到特定位置后,将导航设置为固定

[英]Setting nav to fixed after scrolling to a certain position

I'm designing a landing page using a Flexbox based CSS Framework - Bulma . 我正在使用基于Flexbox的CSS Framework- Bulma设计登录页面。

I created a navbar below a fullheight section and I'm using it to scroll through sections, which gets fixed/unfixed depending whether the page is scrolled below the fullheight section . 我在fullheight部分下方创建了一个导航栏,并使用它来滚动查看各部分,这取决于页面是否在fullheight部分下方滚动而得到固定/未固定。 This is the JQuery code I'm using to add/remove the fixed position class: 这是我用来添加/删除固定位置类的JQuery代码:

$(window).scroll(function () {
    if ($(window).scrollTop() > $('#cover').height()) {
        $('#navbar-sticky').addClass('is-fixed');
    }
    if ($(window).scrollTop() < $('#cover').height()) {
        $('#navbar-sticky').removeClass('is-fixed');
    }
});

The issue I'm facing is that when the navigation bar is set to position: relative - default position, when clicking on any link to a section it "overscrolls" using the height of the navigation bar. 我面临的问题是,当导航栏设置为position: relative默认位置时,单击指向某个部分的任何链接时,它会使用导航栏的高度“过度滚动”。

Another issue is that when navigating to the first section - where the class is toggled, there's also an overscroll, I believe using if ($(window).scrollTop() >= $('#cover').height()) (is greater than or equal to) fixes that. 另一个问题是,导航到第一部分-切换类时,还会发生过度滚动,我相信使用if ($(window).scrollTop() >= $('#cover').height()) (大于或等于)修复该问题。

Here's a relevant codepen that describes my issue https://codepen.io/miraris/full/wrLdwN I'm also using a smooth-scroll library in that codepen, but that's irrelevant and the issue is the same when it's removed (just no offset). 这是一个描述我的问题的相关Codepen https://codepen.io/miraris/full/wrLdwN我也在该Codepen中使用了平滑滚动库 ,但这无关紧要,并且在删除该问题时也是如此(只是没有偏移)。

When an element's position is changed to Fixed, a portion equal to it's height is freed from DOM and elements below it shift up. 当元素的位置更改为固定时,等于其高度的部分将从DOM中释放出来,并且其下面的元素向上移动。

We can have a wrapper to fill the space created by navbar becoming fixed. 我们可以有一个包装器来填充导航栏固定后所创建的空间。

Html HTML

<div class="navbar-space-fill hidden"></div>
<div id="navbar-sticky">
.... your HTML ....
</div>

Javascript Java脚本

On page load- 页面加载-

$('.navbar-space-fill').css({'height':$('#navbar-sticky').height()});

When position of navbar becomes fixed - 当导航栏的位置固定时-

$('.navbar-space-fill').removeClass('hidden');

else - 否则-

$(".navbar-space-fill").addClass("hidden");

要将导航保持在窗口顶部,您只需要删除offset属性即可。

var scroll = new SmoothScroll('a[href*="#"]', {});

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

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