Animate/Shrink NavBar on scroll using Bootstrap 4

2019-01-03 18:15发布

I've searched a whole heap for this but cant seem to find a working solution. Basically I've got my NavBar perfectly how I want it. I now want to shrink the NavBar when my page scrolls down to make it more slim using a nice smooth transition (animation).

This is my HTML markup for my current NavBar:

<header>


      <nav class="navbar fixed-top navbar-toggleable-md navbar-inverse bg-inverse">
          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
          </button>
          <a class="navbar-brand" href="#"><img class="animated bounceIn" src="img/logo-light.png" alt="I Web You &#8211; Perth Website Branding"></a>

          <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav ml-auto">
                  <li class="nav-item active">
                      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                  </li>
                  <li class="nav-item">
                      <a class="nav-link" href="#">About</a>
                  </li>
                  <li class="nav-item">
                      <a class="nav-link" href="#">Portfolio</a>
                  </li>
                  <li class="nav-item">
                      <a class="nav-link" href="#">Contact</a>
                  </li>
                  <li class="nav-item">
                      <a class="nav-link" href="#">Blog</a>
                  </li>
              </ul>
          </div>
      </nav>


    </header>

Any ideas how I can achieve this? I've done a lot of searching but most solutions were for Bootstrap 3.

Cheers

3条回答
我想做一个坏孩纸
2楼-- · 2019-01-03 18:30

Both of the above answers looked long and complicated, surely (I thought) there must be a really sleek way to do this now in Bootstrap 4.1 - it's 2018! Well yeh - nah....There are some interesting answers around the net, if you have a look at some of the templates at startbootstrap.com for example.

I didn't see anything vastly different from those above...

Add or remove a class on scroll/ page load...

    var o = function() {
      var mn = $("#mainNav");
      mn.offset().top > 100 ? mn.addClass("navbar-shrink") : mn.removeClass("navbar-shrink");
    };
    o(), $(window).scroll(o);

Then style based on that appended class...

 #mainNav {
       background-color: #0f6f56;
       transition: all 1s ease;
    }

    #mainNav.navbar-shrink {
      background-color: pink;
    }
查看更多
叛逆
3楼-- · 2019-01-03 18:36

Updated 2018

Most of the shrink on scroll Navbar implementations for Bootstrap 3.x are done using the Affix component to change the style of the navbar at a specific scroll position.

However, Affix has been dropped from Bootstrap 4..

"Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead. See the HTML5 Please entry for details and specific polyfill recommendations."

To create a similar Navbar effect in Bootstrap 4, you can use position: sticky (not supported in all browsers) by adding the sticky-top class to the Navbar. This works to "stick" the Navbar when it reaches the top, but doesn't trigger an event to indicate when the it's "stuck". Therefore, JS is needed to change the Navbar style when it's "stuck".


One JS method supported in modern browsers is IntersectionObserver. Use it to "watch" when a hidden trigger element above the Navbar reaches the viewport (when stuck is applied to the html element).

.stuck .sticky-top {
    background-color: #222;
    padding-top: 3px;
    padding-bottom: 3px;
}

Sticky Top Navbar - IntersectionObserver Demo


You could also jQuery plugin such as ScrollPos-Styler, or write your own jQuery to control the navbar styles on scroll...

How it works:

A fixed-top Navbar with data-toggle="affix":

<div class="navbar navbar-dark bg-dark fixed-top navbar-expand-sm py-3" data-toggle="affix">
      <a href="#" class="navbar-brand">Brand</a>
      <a class="navbar-toggler" data-toggle="collapse" data-target=".navbar-collapse">☰</a>
      <ul class="nav navbar-nav">
          <li class="nav-item"><a href="#" class="nav-link">..</a>
          </li>
      </ul>
</div>

jQuery to watch scroll position and conditionally toggle the .affix class:

var toggleAffix = function(affixElement, scrollElement, wrapper) {
    var height = affixElement.outerHeight(),
        top = wrapper.offset().top;

    if (scrollElement.scrollTop() >= top){
        wrapper.height(height);
        affixElement.addClass("affix");
    }
    else {
        affixElement.removeClass("affix");
        wrapper.height('auto');
    }
};

/* use toggleAffix on any data-toggle="affix" elements */
$('[data-toggle="affix"]').each(function() {
    var ele = $(this),
        wrapper = $('<div></div>');

    ele.before(wrapper);
    $(window).on('scroll resize', function() {
        toggleAffix(ele, $(this), wrapper);
    });

    // init
    toggleAffix(ele, $(window), wrapper);
});

CSS to manipulate the affix style (padding/height, color, etc..):

html,body {
    height:100%;
    padding-top:56px; /*height of fixed navbar*/
}

.navbar { 
  -webkit-transition:padding 0.2s ease;
  -moz-transition:padding 0.2s ease; 
  -o-transition:padding 0.2s ease;        
  transition:padding 0.2s ease;  
}

.affix {
  padding-top: 0.2em !important;
  padding-bottom: 0.2em !important;
  -webkit-transition:padding 0.2s linear;
  -moz-transition:padding 0.2s linear;  
  -o-transition:padding 0.2s linear;         
  transition:padding 0.2s linear;  
}

section {
    min-height:calc(100% - 70px);
}

Note: As of Bootstrap 4.0.0, the Navbar has changed slightly as navbar-toggleable-* has change to navbar-expand-

Sticky Top Navbar - jQuery Demo


Finally, you can use a simple jQuery $(window).scroll() function if you know the exact position of when the Navbar needs to stick...

$(window).scroll(function() {
  /* affix after scrolling 100px */
  if ($(document).scrollTop() > 100) {
    $('.navbar').addClass('affix');
  } else {
    $('.navbar').removeClass('affix');
  }
});

https://www.codeply.com/go/62Roy6RDOa


More Bootstrap 4 change Navbar style on scroll examples:
simply sticky after scroll (4.0.0)
shrink height (4.0.0)
shrink height (alpha-6)
transparent over background
change color after scroll
change navbar bg color with scrollspy sections

Related questions:
Fixing navbar to top on scroll
Affix is not working in Bootstrap 4 (alpha)

查看更多
趁早两清
4楼-- · 2019-01-03 18:42

 $(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});
nav.navbar.shrink {
    width: 100%;
    height: 35px;
    background-color: #111;
    box-shadow: 0 1px 0 0 #dadada;
    position: fixed;
    left: 0px;
    transition: all 1.5s ease;

}
nav.navbar.shrink .navbar-brand  img{
  height: 50px;
  width: 120px;
  transition: all 1.5s ease;
}
nav.navbar.shrink a {
  font-size: 14px;
  padding-bottom: 10px !important;
  padding-top: 10px !important;
  transition: all 1.5s ease;
}
nav.navbar.shrink .navbar-toggler {
  margin: 8px 15px 8px 0;
  padding: 4px 5px;
  transition: all 1.5s ease;
}

.header{

	
	height:100px;
}

.navbar-brand{

	padding-left:30px;
	padding-top:30px;
	padding-bottom:30px;

}

.collapse{

	padding-right:30px;
}

.logo{


	width: 170px;
	height: 58px;
}


.hero-container p{
  color:black;
  text-align: center;
  height:auto;
}

.image-container{
	text-align:center;
}

.banner{

	background-image: url(../images/banner.jpg); 
	background-repeat: no-repeat;
	padding-top: 70px;
	padding-left: 30px;
	padding-right:30px;
	padding-bottom: 78px;
	width:100%;
	height:auto;
 }

.banner .row h4,p{

   color: white;
}

.client{

	height: 635px;
	margin-top:74px;
	padding-right:10px;
	padding-left:10px;
}

.btn-primary{

	
	background: transparent;
	width:170px;
	border: 1px solid white;
	color:white;
}


form{
    padding-top:56px;
    padding-bottom:56px;
	padding-left: 30px;
    height:auto;
	}

form,h2,label{
	color:white;
}

.above{
	margin-bottom:34px;
	width:100%;
	height:auto;
	padding-right: 30px;
}

.below{

	width:100%;
	height:auto;
    padding-right: 30px;

}

.heading{
	color: black;
	margin-top: 62px;
}

.lead{
color:black;
}

.form_banner{
    
	background-image: url(../images/form_banner.jpg);
	background-repeat: no-repeat;
	
    width: 100%;
    
}

.contact{
	background-image: url(../images/contact.png);
	background-repeat: no-repeat;
	margin-bottom: 40px;
	margin-top:50px;
	height:auto;
	width:100%;
	padding-left: 313px;
	padding-right:313px;
	padding-top: 64px;
	padding-bottom:64px;
	text-align: center;
}

.contact, h5{

	color:white;
}

hr{
	display: block;
    margin-top: 0.1em;
    margin-bottom: 0.1em;
    margin-left: auto;
    margin-right: auto;
    border-style: inset;
    border-width: 1px;
}

.footer_img{

	padding-left: 30px;
	width:170px;
	height:63px;
}

.footer{
	margin-bottom: 41px;
}
<!doctype HTML>
<html lang="en">
<head>
  <title>Home</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/styles.css">

  
  
</head>

<body>

<div class="container-fluid">

<div class="header container">
<div class="row">
  <nav class="navbar navbar-expand-md navbar-light bg-light fixed-top">
      <a class="navbar-brand" href="#">HeRo</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">
          <li class="nav-item active">
            <a class="nav-link" href="#">Company<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Capabilities</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Customers</a>
          </li>
          <li class="nav-item">
             <a class="nav-link" href="#">Innovation</a>
          </li>
         <li class="nav-item">
            <a class="nav-link" href="#">Contact Us</a>
          </li>
         
         
        </ul>
        
      </div>
    </nav>
</div>
</div>
</div>
    
<div class="hero-container container">
<div class="row">
  <div class="col">
    
    <p>Commerce</p>
    <p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.</p>
    <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
  </div>

  <div class="col">
  
            <p>Interactive</p>
            <p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.</p>
            <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p></div>
    <div class="col">
    

            <p>Analytics</p>
            <p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.</p>
            <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p></div>
    <div class="col">
    
            <p>Integration</p>
            <p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.</p>
            <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p></div>
    <div class="col">
    
            <p>Cloud & Management Services</p>
            <p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.</p>
            <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p></div>
</div>
</div>
    
<div class="banner container-fluid">
    <div class="row">
        <h4>Dedicated, Experience, Innovative</h4>
        <p>For over a decade our experienced team has been delivering Digital Commerce solutions that change the way consumers research, interact and purchase. As mobility and pervasive connectivity continue to transform buying habits, we are focused on helping businesses discover and maximise new opportunities – be it direct to consumers, via resellers, or by other innovative models.</p>

          <p>Our expertise is centred on the Digital Commerce solution that excels in delivering best-in-class Scalability and User Experience. From our global headquarters in India, we have expanded to empower Clients across four continents, with offices located in Singapore, USA, Australia and the UK.</p>
        <h4>BUSINESS</h4>
        <p>Our approach is to listen to you as the experts in your market. We look to complement your insight with a project team capable of understanding your business and delivering better digital experience. Our in-country Advisors will help assess your requirements and collaboratively design a service that meets your strategic goals.</p>

        <h4>TECHNOLOGY</h4>
        <p>With a specialised team of Creative Designers, Developers, Engineers and Architects we have substantial experience across many leading enterprise and open source platforms. Beyond our core expertise in Digital Commerce, we also offer Mobility, Integration, Digital Analytics, Development and other custom Web and applications development services.</p>
    </div>
</div>



 <!-- FOOTER -->
<div class="footer container">
     
  <div class="clearfix">
    <span class="float-left"><a href="#"><img class="footer_img" src="images/ibm_logo.png"></a></span>
    <span class="float-right">&copy; AbcXyZ Inc and Affiliates.All Rights Reserved</span>
 </div>

</div>


<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.12.9/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>


  
</body>
</html>

Use this code.It's simple and easy. I hope you would get a understanding. I have made a class shrink which it would add to the navbar once it crosses 50 pixels. And rest is all css, which I have put in the Shrink class.

查看更多
登录 后发表回答