¿Cómo crear un Affix o Sticky Navbar?

Para crear un afijo o una barra de navegación adhesiva, debe usar HTML, CSS y JavaScript. HTML hará la estructura del cuerpo, CSS hará que se vea bien. Este tipo de barra de navegación pegajosa se ve atractiva en el sitio web. Mediante el uso de JavaScript, puede hacer que la barra de navegación sea fácilmente pegajosa cuando el usuario se desplaza hacia abajo.
Creación de estructura: en esta sección, crearemos una estructura de sitio web básica para la barra de navegación fija cuando el usuario se desplaza hacia abajo en la página, mostrará el efecto. 
 

  • Código HTML para hacer la estructura: 
     

html

<!DOCTYPE html>
<html>
 
<head>
    <title>How To Create a Affix Navbar</title>
     
    <meta name="viewport"
        content="width=device-width, initial-scale=1">
         
        <!-- Google fonts -->
    <link href=
"https://fonts.googleapis.com/css?family=Special+Elite&display=swap"
        rel="stylesheet">
</head>
 
<body>
    <div class="header">
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20191128123949/cover1.png">
    </div>
 
    <div id="navlist">
        <b>GeeksforGeeks</b>
        <a href="javascript:void(0)">Contact us</a>
        <a href="javascript:void(0)">Careers</a>
        <a href="javascript:void(0)">Our Product</a>
        <a href="javascript:void(0)">About us</a>
        <a href="javascript:void(0)">Home</a>
    </div>
 
    <div class="scrollable"
            style="padding:15px 15px 4500px;">
         
        <b>BLACK FRIDAY</b>
         
         
<p>
            Want to get huge discounts on GeeksforGeeks
            Courses? This Black Friday, we are bringing
            the shopping festival to you!!! GeeksforGeeks
            is celebrating Black Friday on 29th November
            2019 by providing you huge discounts on all
            its courses for the entire day! This will be
            a great opportunity for you to learn and
            enhance your skills. And that’s not all we
            are offering!
        </p>
 
         
         
<p>
            There will also be Flash Sales that will go
            live for a particular duration of time where
            you can expect heavy discounts over a few
            courses in addition to the existing discounts.
            These Flash Sales will go live for 4 times
            during the entire day with different courses
            in each flash sale. Want to know more about
            Black Friday? Read on to find out!
        </p>
 
         
         
<p>
            Black Friday is the Friday immediately after
            Thanksgiving in the United States, which is
            on 29th November this time. This Black Friday
            Sale is intended to provide you with the best
            courses along with great deals where the
            investment of your time and money will surely
            pay off. So Grab this opportunity, Grab the
            deals and celebrate this Black Friday in the
            most amazing way possible!!!
        </p>
 
 
        <center>
            <h3>Black Friday Sale Highlights</h3>
        </center>
         
         
<p>
            This Black Friday, GeeksforGeeks is here with
            some Red Hot new deals on online and offline
            courses. Unbelievable offers will also be back
            in Flash Sales but you need to be quick to get
            them. Here’s everything you need to know about
            the Black Friday sale by GeeksforGeeks:
        </p>
 
         
        <h4>All Day Super Sale On All Courses:</h4>
         
<p>
            There will be a Super Sale on all the available
            courses for the whole day of Black Friday. So
            you can buy your favorite courses at premium
            prices and learn a lot!
        </p>
 
 
        <h4>4 Flash Sales On Selected Courses:</h4>
         
<p>
            There will be In Between Flash Sales on different
            courses for 1 hour each on Black Friday. These
            sales will reduce the prices of already discounted
            courses even further. Stay tuned to find out the
            times for different courses on the Flash Sale!
            There are Limited seats so the discount will be
            available on First Come First Serve basis.
        </p>
 
         
        <h4>Social Media Contest:</h4>
         
<p>
            There will also be a Social Media Contest about
            “Guessing the Price of a Course” on the Black
            Friday Sale. Try your Luck!! Hefty discounts will
            be live on the following courses for the complete
            day. Grab them and pave the way to your dream
            product-based company!
        <hr>
         
        <i>
            All the details you will get by clicking this
            <a href=
"https://www.geeksforgeeks.org/black-friday-sale-programmers-have-carts-geeksforgeeks-has-deals/">
            link</a>
        </i>
    </div>
</body>
 
</html>

Estructura de diseño: En la sección anterior, hemos creado la estructura del sitio web básico. En esta sección, diseñaremos la estructura de la barra de navegación y haremos el efecto de desplazamiento hacia abajo en la barra de navegación usando JavaScript. 
 

  • Código CSS para que quede bien la estructura: 
     

css

<style>
    body {
        margin: 0;
    }
          
    .header {
        text-align: center;
        width: 100%;
    }
          
    #navlist {
        overflow: hidden;
        background-color: #0074D9;
    }
          
    /* navlist designing */
    #navlist a {
        float: right;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        font-size: 17px;
    }
          
    /* navlist link hover effect */
    #navlist a:hover {
        background-color: #ddd;
        color: black;
    }
          
    #navlist b{
        margin-top: 4px;
        padding: 8px 12px;
        color:lime;
        float: left;
        font-size: 22px;
    }
     
    /* scroll portion design */
    .scrollable b {
        font-family: 'Special Elite', cursive;
        font-size: 28px;
    }
          
    .content {
        padding: 16px;
    }
          
    .sticky {
        position: fixed;
        top: 0;
        width: 100%;
    }
</style>
  • Código JavaScript para la barra de navegación adhesiva: 
     

javascript

<script>
    window.onscroll = function() {myFunction()};
  
    var navlist = document.getElementById("navlist");
    var sticky = navlist.offsetTop;
  
    /* Function to stick the nav bar */
    function myFunction() {
        if (window.pageYOffset >= sticky) {
            navlist.classList.add("sticky")
        }
        else {
            navlist.classList.remove("sticky");
        }
    }
</script>
  • Combinación del código HTML, CSS y JavaScript: este ejemplo combina las secciones anteriores para crear un sitio web con barra de navegación fija.

html

<!DOCTYPE html>
<html>
  
<head>
    <title>How To Create a Affix Navbar</title>
      
    <meta name="viewport"
        content="width=device-width, initial-scale=1">
          
        <!-- Google fonts -->
    <link href=
"https://fonts.googleapis.com/css?family=Special+Elite&display=swap"
        rel="stylesheet">
         
    <style>
        body {
            margin: 0;
        }
         
        .header {
            text-align: center;
            width: 100%;
        }
         
        #navlist {
            overflow: hidden;
            background-color: #0074D9;
        }
         
        /* navlist designing */
        #navlist a {
            float: right;
            display: block;
            color: #f2f2f2;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
            font-size: 17px;
        }
         
        /* navlist link hover effect */
        #navlist a:hover {
            background-color: #ddd;
            color: black;
        }
         
        #navlist b{
            margin-top: 4px;
            padding: 8px 12px;
            color:lime;
            float: left;
            font-size: 22px;
        }
         
        /* scroll portion design */
        .scrollable b {
            font-family: 'Special Elite', cursive;
            font-size: 28px;
        }
         
        .content {
            padding: 16px;
        }
         
        .sticky {
            position: fixed;
            top: 0;
            width: 100%;
        }
    </style>
</head>
  
<body>
    <div class="header">
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20191128123949/cover1.png">
    </div>
  
    <div id="navlist">
        <b>GeeksforGeeks</b>
        <a href="javascript:void(0)">Contact us</a>
        <a href="javascript:void(0)">Careers</a>
        <a href="javascript:void(0)">Our Product</a>
        <a href="javascript:void(0)">About us</a>
        <a href="javascript:void(0)">Home</a>
    </div>
  
    <div class="scrollable"
            style="padding:15px 15px 4500px;">
          
        <b>BLACK FRIDAY</b>
          
         
<p>
            Want to get huge discounts on GeeksforGeeks
            Courses? This Black Friday, we are bringing
            the shopping festival to you!!! GeeksforGeeks
            is celebrating Black Friday on 29th November
            2019 by providing you huge discounts on all
            its courses for the entire day! This will be
            a great opportunity for you to learn and
            enhance your skills. And that’s not all we
            are offering!
        </p>
 
          
         
<p>
            There will also be Flash Sales that will go
            live for a particular duration of time where
            you can expect heavy discounts over a few
            courses in addition to the existing discounts.
            These Flash Sales will go live for 4 times
            during the entire day with different courses
            in each flash sale. Want to know more about
            Black Friday? Read on to find out!
        </p>
 
          
         
<p>
            Black Friday is the Friday immediately after
            Thanksgiving in the United States, which is
            on 29th November this time. This Black Friday
            Sale is intended to provide you with the best
            courses along with great deals where the
            investment of your time and money will surely
            pay off. So Grab this opportunity, Grab the
            deals and celebrate this Black Friday in the
            most amazing way possible!!!
        </p>
 
  
        <center>
            <h3>Black Friday Sale Highlights</h3>
        </center>
          
         
<p>
            This Black Friday, GeeksforGeeks is here with
            some Red Hot new deals on online and offline
            courses. Unbelievable offers will also be back
            in Flash Sales but you need to be quick to get
            them. Here’s everything you need to know about
            the Black Friday sale by GeeksforGeeks:
        </p>
 
          
        <h4>All Day Super Sale On All Courses:</h4>
         
<p>
            There will be a Super Sale on all the available
            courses for the whole day of Black Friday. So
            you can buy your favorite courses at premium
            prices and learn a lot!
        </p>
 
  
        <h4>4 Flash Sales On Selected Courses:</h4>
         
<p>
            There will be In Between Flash Sales on different
            courses for 1 hour each on Black Friday. These
            sales will reduce the prices of already discounted
            courses even further. Stay tuned to find out the
            times for different courses on the Flash Sale!
            There are Limited seats so the discount will be
            available on First Come First Serve basis.
        </p>
 
          
        <h4>Social Media Contest:</h4>
         
<p>
            There will also be a Social Media Contest about
            “Guessing the Price of a Course” on the Black
            Friday Sale. Try your Luck!! Hefty discounts will
            be live on the following courses for the complete
            day. Grab them and pave the way to your dream
            product-based company!
        <hr>
          
        <i>
            All the details you will get by clicking this
            <a href=
"https://www.geeksforgeeks.org/black-friday-sale-programmers-have-carts-geeksforgeeks-has-deals/">
            link</a>
        </i>
    </div>
     
    <script>
        window.onscroll = function() {myFunction()};
 
        var navlist = document.getElementById("navlist");
        var sticky = navlist.offsetTop;
 
        /* Function to stick the nav bar */
        function myFunction() {
            if (window.pageYOffset >= sticky) {
                navlist.classList.add("sticky")
            }
            else {
                navlist.classList.remove("sticky");
            }
        }
    </script>
</body>
  
</html>

Producción: 
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *