您好,我想知道如何在我的标头中使用 PHP,以便我的类活动可以在正确的页面上被激活。
例如在我的索引上.php我在顶部有这个
<?php
$page = 'Home';
include("header.php");
?>
然后这是我的导航
<nav>
<ul>
<li><a class="active" href="index">Home</a></li>
<li class="rightside"><a href="projects">Projects</a></li>
<li class="rightside"><a href="about_us">About</a></li>
<li class="rightside"><a href="blog">Blog</a>
<li class="rightside"><a href="contact">Contact</a>
</ul>
</nav>
我希望当我在适当的页面上时激活该类,如果这有任何意义的话。谢谢,我的PhP知识很少。
这是一个可以内联使用的速记if
语句
<?php echo ($page == 'Home' ? 'active':'');?>
见下文
<nav>
<ul>
<li><a class="<?php echo ($page == 'Home' ? 'active':'');?>" href="index">Home</a></li>
<li class="rightside"><a class="<?php echo ($page == 'Projects' ? 'active':'');?>" href="projects">Projects</a></li>
<li class="rightside"><a class="<?php echo ($page == 'About_us' ? 'active':'');?>" href="about_us">About</a></li>
<li class="rightside"><a class="<?php echo ($page == 'Blog' ? 'active':'');?>" href="blog">Blog</a>
<li class="rightside"><a class="<?php echo ($page == 'Contact' ? 'active':'');?>" href="contact">Contact</a>
</ul>
</nav>
我个人为此使用 jquery 函数,它节省了每次声明页面类型的时间
jQuery
$(function () {
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('[href$="'+url+'"]').parent().addClass("active");
});
如果总是在标头包含之前声明$page,则可以使用 if 语句。举个例子:
<nav>
<ul>
<li><a class="<?php echo ($page == 'Home') ? 'active' : 'rightside'; ?>" href="index">Home</a></li>
<!-- same for your other list elements -->
</ul>
</nav>