我有一个导航栏
<?php
function echoActiveClassIfRequestMatches($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="active"';
}
?>
<section id="navigation">
<div class="container">
<div class="row">
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li <?=echoActiveClassIfRequestMatches("index")?>><a href="index.php">Home</a></li>
<li <?=echoActiveClassIfRequestMatches("services")?>><a href="services.php">Services</a></li>
<li <?=echoActiveClassIfRequestMatches("information")?>><a href="information.php">Information</a></li>
<li <?=echoActiveClassIfRequestMatches("contact")?>><a href="contact.php">Contact Info</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="active">Call Us Today! <br> (123) 456-789</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
</div>
</section>
当网址为mydomain.com/index.php
并休息时,此方法有效。
打开页面时出现问题mydomain.com/
主页按钮无效。
只有在我点击主页时它才会变为活动状态。它重定向到mydomain.com/index.php
当网址为mydomain.com/
或mydomain.com/index.php
由于
答案 0 :(得分:0)
$activeTab = explode('/',ltrim($_SERVER['REQUEST_URI'],'/'));
// loop through each tabs
$activeTabs = array("index", "services","information","contact"); // set home as 'index', but can be changed based of the home uri
foreach ($activeTabs as $folder){
$active[$folder] = ($activeTab[0] == $folder)? "active":"noactive";
}
<ul>
<li <?=active("index")?>><a href="index.php">Home</a></li>
<li <?=active("services")?>><a href="services.php">Services</a></li>
<li <?=active("information")?>><a href="information.php">Information</a></li>
<li <?=active("contact")?>><a href="contact.php">Contact Info</a></li>
</ul>
答案 1 :(得分:0)
将此行添加到您的html:
<li <?= echo $_SERVER['REQUEST_URI'] == '/' ? 'class="active"' : '' ?>><a href="index.php">Home</a></li>