开发者

Highlighting current menu item if PHP include

If i make a menu nav in html and use PHP to i开发者_JS百科nclude it in every page on my website, how do i go about highlighting the current page if all i can put on the page is include("menu.html");


Make your menu.html into menu.php and within that file do something like

<ul class="menu">
    <li <?php echo ($page == 'page1') ? 'class="current"' : '';?>> <a href="#">Page1</a> </li>
    <li <?php echo ($page == 'page2') ? 'class="current"' : '';?>> <a href="#">Page2</a></li>   
</ul>

That way in each page you include your menu.php you can simply set the variable like so

<?php    
$page = 'page1';
include('menu.php');
?>

Keep in mind that this is just an example since we don't know what your current code looks like


You can also write the menu in PHP since you are already using PHP to load the menu simply run an if/else statement on the menu-items to check if the "href" in the link matches the current URL of the page and set the menu item to "active".


In raw php this should be like

<?php 
$currentPage = ''; // should be accessed from $_SERVER
$cssMenu = array('home.html', 'about.html');
if(array_search($currentPage, $cssMenu)) $cssMenu[$currentPage] = 'active';
?>

<ul id="top-menu">
<li class="<?= $cssMenu['home.html'] ?>">Home</li>
<li class="<?= $cssMenu['about.html'] ?>">About</li>
</ul>


Since you can't modify classes and divs before the page loads, you'll have to use some sort of javascript/jquery/whatever to dynamically highlight the link after the page is loaded. This shouldn't be too difficult; you can have a bit of Javascript that looks through the menu div (assuming you're using divs) for an href entry which matches the current page, and then add the proper css class to that specific tag.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜