本文介绍了Bootstrap 4-如何使固定式导航栏在滚动时消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Bootstrap 4,如何使固定顶部导航栏在滚动时消失?我已在HTML代码下方附加了默认的Bootstrap 4导航栏.

With Bootstrap 4, how can I make the fixed-top navbar disappear on scroll? I've attached below the html code for the default Bootstrap 4 navbar.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
  <a class="navbar-brand" href="#">Test</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

  <div class="collapse navbar-collapse" id="navbarsExampleDefault">
    <ul class="navbar-nav ml-auto py-md-2">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">About</a>
      </li>
    </ul>
  </div>
</nav>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

推荐答案

提示也打败了我.与他的答案相似,但不使用短代码.

Cue beat me too it. Similar to his answer but not using short code.

jQuery

// scroll functions
$(window).scroll(function(e) {

    // add/remove class to navbar when scrolling to hide/show
    var scroll = $(window).scrollTop();
    if (scroll >= 150) {
        $('.navbar').addClass("navbar-hide");
    } else {
        $('.navbar').removeClass("navbar-hide");
    }

});

CSS导航栏淡出选项

Codeply演示 https://www.codeply.com/go/rTR1dcn4n6

Codeply demo https://www.codeply.com/go/rTR1dcn4n6

.navbar {
    opacity: 1;
    transition: opacity 0.5s ease;
}

.navbar-hide {
    pointer-events: none;
    opacity: 0;
}

CSS导航栏向上滑动选项

Codeply演示 https://www.codeply.com/go/7Fab8Thufl

Codeply demo https://www.codeply.com/go/7Fab8Thufl

.navbar {
    transition: top 0.5s ease;
}

.navbar-hide {
    top: -56px;
}


如果您不喜欢更少的代码,Cue的答案可能会更好,这是下面使用我的hide类的方法.


Cue's answer is probably much better if you like less code, here is his method below using my hide class.

提示的jQuery

// scroll functions
$(window).scroll(function(e) {

    // add/remove class to navbar when scrolling to hide/show
    $('.navbar')[$(window).scrollTop() >= 150 ? 'addClass' : 'removeClass']('navbar-hide');

});

CSS导航栏淡出选项(与上面相同)

Codeply演示 https://www.codeply.com/go/KPnx8ewEED

Codeply demo https://www.codeply.com/go/KPnx8ewEED

CSS导航栏向上滑动选项(与上面相同)

Codeply演示 https://www.codeply.com/go/i82vYBGeu7

Codeply demo https://www.codeply.com/go/i82vYBGeu7

这篇关于Bootstrap 4-如何使固定式导航栏在滚动时消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 14:01