Navbar highlight for current page

前端 未结 3 998
野趣味
野趣味 2021-02-04 12:58

I was wondering how I would add the ability to add a highlight box the nav bar on the page your currently on. You know so people know what page their on.

Very much like

相关标签:
3条回答
  • 2021-02-04 13:14

    You can use the jquery function window.location.href to compare the site you are on right now with your href of < a > in the list element. For example, "index.html":

    <li><a href="index.html">Home</a></li>
    

    The code below searches for the href of the active page in the list elements < a >. Then adds the class "active" with addClass('active') to the active pages < a > so that you can now call it via CSS. Put this code in the head of your html file.

    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script>
        $(function(){
            $('a').each(function(){
                if ($(this).prop('href') == window.location.href) {
                    $(this).addClass('active'); $(this).parents('li').addClass('active');
                }
            });
        });
    </script>
    

    You can now add your css conditions like changing the color:

    #nav_bar .active {
        color:            #F8F8F8;
        background-color: #4f81bd;
    }
    
    0 讨论(0)
  • 2021-02-04 13:22

    I somewhere found a pretty simple code to do it.

    <script>
        $(function () {
            $('nav li a').filter(function () {
                return this.href === location.href;
            }).addClass('active');
        });
    </script>
    
    0 讨论(0)
  • 2021-02-04 13:30

    If you have the same navigation bar in each HTML page of your website, then you can do like this:
    For example in index.html add class='active-page' to the first menu item:

    <div id="nav_bar">
        <ul>
            <li><a href="index.html" class='active-page'>Home</a></li>
            <li><a href="status.html">Status</a></li>
            <li><a href="info.html">Info</a></li>
    

    Then in the status.html add class='active-page' again but for the second item:

    <div id="nav_bar">
        <ul>
            <li><a href="index.html">Home</a></li>
            <li><a href="status.html" class='active-page'>Status</a></li>
            <li><a href="info.html">Info</a></li>
    

    And do this for all of your pages.

    Finally in your css write a class for active-page like this:

    #nav_bar ul li a.active-page
    {
      background-color:blue;
    }
    
    0 讨论(0)
提交回复
热议问题