2016-12-26 58 views
0

我有一個導航欄如何在PHP中基於URL創建活動類?

<?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
$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> 
0

此行添加到您的HTML:

<li <?= echo $_SERVER['REQUEST_URI'] == '/' ? 'class="active"' : '' ?>><a href="index.php">Home</a></li>