Bootstrap CSS Active Navigation

前端 未结 13 2357

On the Bootstrap website the subnav matches up with the sections and changes background color as you or scroll to the section. I wanted to create my own menu without all the

13条回答
  •  无人及你
    2020-11-27 12:35

    I use 2 1-liners, depending on how my nav is structured

    Just make sure that none of your links have active class to start.

    actual links

    If your nav links are on separate HTML files (like a layout template in express.js that has a menu), you can do this:

    $('ul.nav > li > a[href="' + document.location.pathname + '"]').parent().addClass('active');
    

    hash links

    If they are hashes, do this:

    $('ul.nav > li > a[href="' + document.location.hash + '"]').click(function(){  $('ul.nav > li').removeClass('active'); $(this).parent().addClass('active'); });
    

    If you don't want to scroll on hash-click, return false:

     $('ul.nav > li > a[href="' + document.location.hash + '"]').click(function(){  $('ul.nav > li').removeClass('active'); $(this).parent().addClass('active'); return false; });
    

提交回复
热议问题