2015-04-03 11:10 阅读 18


I was wondering if it is possible to "Sync" the content of a Bootstrap navbar instead of having to edit the navbar on all the pages it is on. With PHP this is fairly easy using something like <?php include 'navbar.php';?> However, there are a few kinks I can't work out.

My current navbar.php is:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href=".">Brand</a> </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    ****<li class="active"><a href=".">Item 1<span class="sr-only"> (current)</span></a> </li>
                    <li class="dropdown"><a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#">Item 1</a>
                            <li class="divider"></li>
                            <li class="dropdown-header">Header</li>
                            <li><a href="#">Item 2</a>
                    <li><a href="#">Item 2</a> </li>
                    <li><a href="#">Item 3</a> </li>

The line I have marked with asterisks is an example of the active class and <span class="sr-only"> (current)</span> that need to be added to the page the user is currently on. Is there any way I can do this?



  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongwuchu0314 dongwuchu0314 2015-04-03 13:34

    As a solution you can add page name as a class to every li item and then on page load, parse the page name and set active class to the li element with page-name class.

    smth like this

    <ul class="nav navbar-nav">
        <li class="active page1"><a href="page1.html">Item 1<span class="sr-only"> (current)</span></a> </li>
        <li class="page2"><a href="page2.html">Item 2</a> </li>
    $(function() {
      var path = window.location.pathname;
      var page = path.split("/").pop();
      var pageName = page.substring(0, page.length - 5); // cut .html from the page
      $('.' + pageName).addClass('active');
      $('.' + pageName).append('<span class="sr-only"> (current)</span>'); // add an element for a screenreader
    点赞 评论 复制链接分享