如何使用php + css更改活动菜单的样式

如何使用php + css更改活动菜单的样式

问题描述:

So, I'm writing a menu and I want it to stay a certain color based upon it being on that page. I've added "class = 'active'" onto the page, and I've tried adding it to CSS, but it's not working. Any ideas?

PHP code:

<?php
$currentPage = basename($_SERVER['REQUEST_URI']);
print "<div id = 'submenu-container'>";
print "<div id = 'submenu'>";
print "<ul class = 'about'>";
print "     <li><a  href='about.php#about_intro.php'if($currentPage=='about.php#about_intro.php' || $currentPage=='about.php') echo 'class='active''>About</a></li>";
print "     <li><a href='about.php#about_team.php'if($currentPage=='about.php#about_team.php') echo 'class='active''>Team</a></li>";
print "     <li><a href='about.php#about_services.php' if($currentPage=='about.php#about_services.php') echo 'class='active'>Services</a></li>";            
print " </ul>";
print "</div>";
print"</div>";
?>

CSS:

#submenu ul li a .active {
background:#FFF;    
}

所以,我正在写一个菜单,我希望它基于它在该页面上保持某种颜色 。 我在页面上添加了“class ='active'”,我尝试将其添加到CSS中,但它无效。 有什么想法吗? p>

PHP代码: p>

 &lt;?php 
 $ currentPage = basename($ _ SERVER ['REQUEST_URI'])  ; 
print“&lt; div id ='submenu-container'&gt;”; 
print“&lt; div id ='submenu'&gt;”; 
print“&lt; ul class ='about'&gt;”; 
print  “&lt; li&gt;&lt; a href ='about.php#about_intro.php'if($ currentPage =='about.php#about_intro.php'|| $ currentPage =='about.php')echo'class =  'active''&gt;关于&lt; / a&gt;&lt; / li&gt;“; 
print”&lt; li&gt;&lt; a href ='about.php#about_team.php'if($ currentPage =='about.php#  about_team.php')echo'class ='active''&gt; Team&lt; / a&gt;&lt; / li&gt;“; 
print”&lt; li&gt;&lt; a href ='about.php#about_services.php'if(  $ currentPage =='about.php#about_services.php')echo'class ='active'&gt; Services&lt; / a&gt;&lt; / li&gt;“;  
print“&lt; / ul&gt;”; 
print“&lt; / div&gt;”; 
print“&lt; / div&gt;”; 
?&gt; 
  code>  pre> 
 
  CSS: p> 
 
 
  #submenu ul li a .active {
background:#FFF;  
} 
  code>  pre> 
  div>

$_SERVER['REQUEST_URI'] will never contain the portion after the hash. It will only show up to about.php and any URL arguments passed with the ?. You should create specific pages for each of these, give the about_intro/about_team/about_services in a query string instead of a hash, or add the active class with javascript.

Additionally, don't use an if statement when inside of another statement. Use the ternary operator.

print "<li><a href='about.php'"
    .$currentpage=="about.php"?" class='active'":""
    .">About</a></li>";

print "     <li><a  href='about.php#about_intro.php'if($currentPage=='about.php#about_intro.php' || $currentPage=='about.php') echo 'class='active''>About</a></li>";

doesn't make sense. all this string will be outputted and displayed in html. you must use string concatenation:

$cl = ($currentPage=='about.php#about_intro.php' || $currentPage=='about.php')?" class='active'": "";
print "<li><a  href='about.php#about_intro.php' $cl>About</a></li>";