简体   繁体   中英

Navbar element active while scrolling

I want to make my navbar active while scrolling through my page. How can I do that by using bootstrap? I tried by using React-scroll npm package...but can't able to do it effectively

import React from "react";
import Navbar from "react-bootstrap/Navbar";
import Nav from 'react-bootstrap/Nav';
import Logo from "../../assects/img/Nav/vimal.png"
import "./mynavbar.css";

const MyNavbar=()=>{
    return(
        <div>
            <Navbar fixed='top' collapseOnSelect expand="md" bg="dark" variant="dark">
                <Navbar.Brand href="#home">
                    <img className='logo' src={Logo} alt="logo"/>
                </Navbar.Brand>
                <Navbar.Toggle aria-controls="responsive-navbar-nav" />
                <Navbar.Collapse id="responsive-navbar-nav">
                <Nav className="ml-auto">
                    <Nav.Link href="#home">Home</Nav.Link>
                    <Nav.Link href="#about">About</Nav.Link>
                    <Nav.Link href="#skills">Skills</Nav.Link>
                    <Nav.Link href="#projects">Projects</Nav.Link>
                    <Nav.Link href="#contact">Contact</Nav.Link>
                </Nav>
                </Navbar.Collapse>
            </Navbar>
        </div>
    )
}
export default MyNavbar

A good way to do this would be to use the JQuery scroll() function. An example would be:

$(window).scroll(function() {
    var winHeight = $(this).height();
    var scrollTop = $(this).scrollTop();
    
    var elemHeight = $("#first-section").height();
    var elementTop = $("#first-section").position().top; 
     
    if (elementTop < scrollTop + winHeight && scrollTop < elementTop + elemHeight)
        $("your-div").addclass("active");
    else
        $("your-div").removeClass("active");
    
});

This will add a class called.active{} to your element when the top of the window reaches a certain point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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