如何让我的导航栏在到达元素时粘在元素的底部

How can I make my navbar stick to the bottom of an element upon reaching it?

本文关键字:元素 底部 我的 导航      更新时间:2023-09-26

好的,我正在尝试让我的导航栏粘在页面顶部的 25px 高标题的底部。我只希望我的导航栏在到达该标题的底部时粘住(变得固定 - position: fixed)。

我可以在下面找到我设置的CodePen的链接。对于您将看到的所有额外的CSS和JavaScript/jQuery内容,我深表歉意。不过,这都是网站/设计的一部分。

我只是无法让我的导航栏(位于屏幕底部)在到达屏幕顶部 25px(黑色)标题的底部时变得固定。我已经尝试了来自不同地方的10 +解决方案,但没有一个为我做诀窍......

http://codepen.io/anon/pen/WrZjWG

您需要

做的是向导航添加一个类,因此首先,由于您的导航绝对位于窗口中,我们将找到窗口高度并减去您的导航和顶部栏您拥有,然后从那里添加和删除类。 以下方法将起作用:

$(window).on('scroll', function () {
  if ( $(window).scrollTop() >= $(window).height() - 105) {
    $( '#mainNav' ).addClass("scrolled");
  }else{
    $( '#mainNav' ).removeClass("scrolled");
  }
});

然后你的 css

#mainNav.scrolled { /* This will only take place when the navbar reaches the set point on the page */
  position: fixed;
  z-index: 99;
  top:25px;
  left:0;
}

通常你会使用 $('div').offset().top 而不是 $(window).height() - 105但你的导航绝对位于窗口中,而不是在任何相对div 中,这会导致结果不一致,因此我们会找到窗口高度,然后减去你的导航和顶部栏的高度。 现在,一旦滚动到顶部栏的底部,您的导航应该固定在正确的位置。 这是一个有效的代码

笔代码笔

试试这个脚本

$(function() {
    var offset = $("#navbar").offset(),
        topPadding = 15;
    $(window).scroll(function() {
        if ($("#sidebar").height() < $(window).height() && $(window).scrollTop() > offset.top) {
            $("#sidebar").stop().animate({
                marginTop: $(window).scrollTop() - offset.top + topPadding
            });
        } else {
            $("#sidebar").stop().animate({
                marginTop: 0
            });
        };
    });
});

有一个 nacent(在 Firefox、Safari 和 iOS6+ 中支持;在 Chrome 中开发中;边缘中的"正在考虑中";更多数据在 caniuse.com) CSS 属性可以实现这一点:

position: sticky

还有一些 polyfill 可以模拟其他浏览器中position: sticky的行为:

  • https://github.com/filamentgroup/fixed-sticky
  • https://github.com/wilddeer/stickyfill

这些都比上面几个手动滚动的建议要强大得多。

有效!在 jquery 中添加 #landingHeaderWrapper 的高度,就像我在这里所做的那样
http://codepen.io/vishnu1212/pen/jWGwop然后添加一个具有位置属性的新类,例如

.sticky{ postion:fixed;}

使用 AddClass 和 removeClass 函数切换此类