简体   繁体   English

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

[英]How to change the style of an active menu with 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. 我在页面上添加了“class ='active'”,我尝试将其添加到CSS中,但它无效。 Any ideas? 有任何想法吗?

PHP code: PHP代码:

<?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: CSS:

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

$_SERVER['REQUEST_URI'] will never contain the portion after the hash. $_SERVER['REQUEST_URI']将永远不会包含散列后的部分。 It will only show up to about.php and any URL arguments passed with the ? 它只会显示about.php和任何传递的URL参数? . 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. 您应该为每个页面创建特定页面,在查询字符串中提供about_intro / about_team / about_services而不是哈希,或者使用javascript添加活动类。

Additionally, don't use an if statement when inside of another statement. 另外,在另一个语句中不要使用if语句。 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. 所有这个字符串都将输出并以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>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM