开发者

Set a class for an element in a PHP include()

开发者 https://www.devze.com 2022-12-26 20:52 出处:网络
I have an identical horizontal menu at the top of all of my pages, which I add using a PHP include() statement.In my stylesheet I want to have a class where if the user is on a particular page开发者_G

I have an identical horizontal menu at the top of all of my pages, which I add using a PHP include() statement. In my stylesheet I want to have a class where if the user is on a particular page开发者_Go百科, the menu item corresponding to that page will have a different color. So, more or less:

#menu { background-color:blue; }

#menu .active { background-color:green; }

But, since the menu comes from the PHP include, it's always the same. How can I write some PHP or JavaScript that adds class="active" to the appropriate menu item for each page?


When you include() a file, the included file has access to all the in-scope variables at the place where it gets included. You could easily set a variable to say which menu item should be active. A basic example might be something like this:

firstpage.php

<?php

$chosenMenu = 'page1';
include('menu.php');

menu.php

<div id="menu">
<?php
$menuItems = array(
    'page1'=>'firstpage.php',
    'page2'=>'secondpage.php',
    'page3'=>'lolcats.php'
);
foreach($menuItems as $key => $value) {
    echo '<a href="'.$value.'"';
    if (isset($chosenMenu) && $chosenMenu == $key) echo ' class="active"';
    echo '>';
}
?>
</div>

With this style, you can simply set a variable $chosenMenu before including your menu file, and you can control it from there.

0

精彩评论

暂无评论...
验证码 换一张
取 消