当子项处于活动状态时,使用PHP将活动类添加到父元素和子元素

时间:2015-10-06 14:18:16

标签: php html drop-down-menu submenu

是否存在子元素Subpage1.phpSubpage2.php处于活动状态的解决方案,以便父元素practices.php也获得class="active"

<ul>
    <li class="<?php echo ($_SERVER['PHP_SELF'] == " /index.php " ? "active " : " ");?>">
        <a href="index.php">Start</a>
    </li>
    <li class="<?php echo ($_SERVER['PHP_SELF'] == " /practices.php " ? "active " : " ");?>">
        <a href="practices.php">Practices</a>
        <ul>
            <li class="<?php echo ($_SERVER['PHP_SELF'] == " /subpage1.php " ? "active " : " ");?>">
                <a href="subpage1.php">Subpage1</a>
            </li>
            <li class="<?php echo ($_SERVER['PHP_SELF'] == " /subpage2.php " ? "active " : " ");?>">
                <a href="subpage2.php">Subpage2</a>
            </li>
        </ul>
    </li>
</ul>

A similar question was asked here, but the parent child problem couldn't be solved there

1 个答案:

答案 0 :(得分:0)

这不是最佳选择,但您可以使用in_array()检查元素及其子元素的$_SERVER['PHP_SELF']值:

<li class="<?php echo (in_array($_SERVER['PHP_SELF'], array(
        '/practices.php',
        '/subpage1.php',
        '/subpage2.php',
    )) ? "active " : " ");?>">
    <a href="practices.php">Practices</a>
    ...
</li>

如果$_SERVER['PHP_SELF']与该数组中的任何项匹配,则该类将设置为活动状态。它可能不如循环麻烦。