开发者

How do I use PHP to build a website menu with dynamic highlighting?

开发者 https://www.devze.com 2023-02-06 10:00 出处:网络
I need to changecolor of selected menu whenever that page is active and it should stay until another menu is clicked.I have used jquery like

I need to change color of selected menu whenever that page is active and it should stay until another menu is clicked.I have used jquery like

$('.navigation ul li a').click(function(){

 $(this).css({"background-color":"#ffffff"});
 $('.navigation ul li a').css({"background":"transparent"});

});

But it works only 开发者_运维问答for the click function only.I need it to be active till i move to another menu .plz help!!!


PHP Only

Let us assume that your website has the following menu:

  • Home
  • Pistols
  • Rifles

At the top of the Home HTML page, insert:

<?php $this_page = "Home"; ?>

At the top of the Pistols HTML page, insert:

<?php $this_page = "Pistols"; ?>

At the top of the Rifles HTML page, insert:

<?php $this_page = "Rifles"; ?>

In your css-file, add an id, with the accompanying format, for the menu item whose page is the one displayed in the browser. Call this id #cur_item, for example.

Edit your navigation HTML to look like this:

<ul class="navigation">
    <li <?php if ($this_page == "Home"):?> id="cur_item" <?php endif; ?> >
        Home
    </li>
    <li <?php if ($this_page == "Pistols"):?> id="cur_item" <?php endif; ?> >
        Pistols
    </li>
    <li <?php if ($this_page == "Rifles"):?> id="cur_item" <?php endif; ?> >
        Rifles
    </li>
</ul>


You don't need to use any jQuery, just CSS.

  • give your body tag and id for the page i.e. body id="contact"
  • give each menu link a class that matches the body id
  • Write the CSS for your active links:

'

body#home .navigation ul li a.home, 
body#services .navigation ul li a.services,
body#contact .navigation ul li a.contact {
    background-color: #ffffff
}

'


You need to use css a:active tag for this


$('.navigation ul li a').click(function () {

    $('.navigation ul li a').each(function () { // loop through all links
       if ($(this).hasClass('active')) $(this).removeClass('active'); // remove className 'active' from any link
    });

    $(this).addClass('active'); // className active to current link
});

CSS

.navigation ul li a {
    background: transparent;
}

.navigation ul li a.active {
    background-color: #ffffff;
}
0

精彩评论

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