如何将活动类添加到菜单项

时间:2017-02-15 17:03:06

标签: javascript php twitter-bootstrap

我的菜单位于名为menu.php的包含文件中,我想分配一个名为&#39; active&#39;到<li>到我所在的页面。我怎么能用PHP或JavaScript做到这一点?

&#13;
&#13;
<!-- navigation -->
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" 
        data-target="#collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right">
  <li><a href="index.php">Home</a></li>
  <li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" 
         aria-haspopup="true" aria-expanded="false">Insect Control 
      <span class="caret"></span></a>
    <ul class="dropdown-menu">
      <li><a href="insect-control.php">Insect Control</a></li>
      <li><a href="ant-cockroach-control.php">Ant & Cockroach Control</a></li>
      <li><a href="bed-bug-treatment.php">Bed Bug Treatments</a></li>
      <li><a href="fly-control.php">Fly Control</a></li>
      <li><a href="wasp-hornets-bee-control.php">Wasp, Hornet & Bee Control</a></li>
    </ul>
  </li>
  <li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" 
         aria-haspopup="true" aria-expanded="false">Rodent & Vermin 
      <span class="caret"></span></a>
    <ul class="dropdown-menu">
      <li><a href="rodent-vermin.php">Rodent & Vermin</a></li>
      <li><a href="rats-mice-infestation.php">Rats & Mice Infestation</a></li>
      <li><a href="squirrel-control.php">Squirrel Control</a></li>
    </ul>
  <li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
<!-- end navigation -->
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您可以在menu.php include之前设置一个变量,告诉include要突出显示的内容: -

$activepage = "squirrel-control";
require("menu.php");

然后在菜单上: -

<li <?=($activepage=="rodent-and-vermin")?'class="active"':''?>><a href="rodent-vermin.php">Rodent & Vermin</a></li>
<li <?=($activepage=="rats-mice-infestation")?'class="active"':''?>><a href="rats-mice-infestation.php">Rats & Mice Infestation</a></li>
<li <?=($activepage=="squirrel-control")?'class="active"':''?>><a href="squirrel-control.php">Squirrel Control</a></li>

答案 1 :(得分:0)

这是您可能正在寻找的JavaScript代码。

var requestURI = "<?= basename($_SERVER['REQUEST_URI']) ?>";
var navList = document.querySelectorAll("ul.nav li");

for(var i = 0; i < navList.length; i++) {
    var menuURL = navList[i].querySelector('a').href;
    menuURL = menuURL.substring(menuURL.lastIndexOf('/') + 1);
    if(requestURI == menuURL) {
        navList[i].classList.add('active');
    }
}

在第1行,该PHP代码用于返回所请求页面的名称。您也可以通过以下方式单独使用JavaScript:

var requestURI = window.location.pathname;
requestURI = requestURI.substring(requestURI.lastIndexOf('/') + 1);

因此,您可以使用JavaScript本身完成所有操作。

希望它有所帮助!