使用PHP在导航中设置活动类

使用PHP在导航中设置活动类,php,Php,您好,我想知道如何在我的标题中使用PHP,以便在正确的页面上激活我的活动类 例如,在my index.php上 我在上面有这个 <?php $page = 'Home'; include("header.php"); ?> 这就是我的导航 <nav> <ul> <li><a class="active" href="index">Hom

您好,我想知道如何在我的标题中使用PHP,以便在正确的页面上激活我的活动类

例如,在my index.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知识很少。

如果你总是在头include之前声明$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>


这是一个可以内联使用的缩写
if
语句

<?php echo ($page == 'Home' ? 'active':'');?>

已经有许多教程可用于此。您需要使用PHP来确定您所处的页面,然后
if
page=this one class=which。不过,有更聪明的方法,但这取决于您是使用某种模板/框架系统,还是将所有内容内联
            <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>
$(function () {
  var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
  $('[href$="'+url+'"]').parent().addClass("active");
});