0

我有四个 php 页面,homepage.inc.php、about.inc.php、contact.inc.php 和我的 index.php

<div id="menu">
    <nav>
        <a id="home" target="_self" href="index.php">Home</a>
        <a id="about" target="_self" href="index.php?p=about">About us</a>
        <a id="contact" target="_self" href="index.php?p=contact">Contact</a>
    </nav>
</div>

<div id="content">
    <?php
    $pages_dir = 'pages';
    if (!empty($_GET['p'])) {
        $pages = scandir($pages_dir, 0);
        unset($pages[0], $pages[1]);
        $p=$_GET['p'];


        if(in_array($p.'.inc.php', $pages)){
            include($pages_dir.'/'.$p.'.inc.php');


        }else {
         echo 'Sorry, page not found.';
        }
    }else{
        include($pages_dir.'/home.inc.php');
        }
    ?>

</div>

这是我的 css active{background:gray;} 我想在我的菜单上添加一个活动类。如何?

4

2 回答 2

1

你可以这样做:

<a id="contact" target="_self" href="index.php?p=contact" <?php if ($_GET['p'] == "contact") {
    echo  'class="active"';
    } ?> >Contact</a>

或者使用简写 PHP(使代码看起来更干净)

<a id="contact" target="_self" href="index.php?p=contact"<? (($_GET['p']=="contact") ? 'class="active"' : '') ?>>Contact</a>

或者您可以将一些 JavaScript 与 JQuery 一起使用:

<script>
$('#<?php echo $_GET['p'] ?>').addClass('active');
</script>
于 2013-05-18T14:00:32.690 回答
0

更改您的代码如下所示 ">首页 ">关于我们 ">联系我们

<?php
$homeCls = '';
$aboutCls = '';
$contactCls= '';
    $pages_dir = 'pages';
    if (!empty($_GET['p'])) {
        $pages = scandir($pages_dir, 0);
        unset($pages[0], $pages[1]);
        $p=$_GET['p'];

       if($p == '') {
     $homeCls = 'active';
       } else if($p == 'about'){
         $aboutCls = 'active';
       } else if($p == 'contact'){
         $contactCls= 'active';
       }
        if(in_array($p.'.inc.php', $pages)){
            include($pages_dir.'/'.$p.'.inc.php');


        }else {
         echo 'Sorry, page not found.';
        }
    }else{
        include($pages_dir.'/home.inc.php');
        }
    ?>
于 2013-05-18T14:04:22.360 回答