简体   繁体   中英

Current page highlighted in menu

I'm trying to get my menu to highlight the current selected page from that menu.

http://jsfiddle.net/ePtFq/

My HTML code looks like so:

<div class="menu-container">
    <div class="menu-wrapper">
        <ul id="menu">
            <li class="current"><a href="#">HOME</a></li>
            <li><a href="#">ABOUT US</a></li>
            <li><a href="#">SERVICES</a></li>
            <li><a href="#">CONTACT US</a></li>
            <li><a href="#">PHOTOS</a></li>
        </ul>
    </div>
</div>

Firstly, is this the proper way of doing the highlight the current page in menu ? The plan is for each html page to have the class="current" manually changed to that respective page.

Secondly, how do I get the format to change? What order does the #menu , li and .current have to appear in? I've tried:

#menu li .current{
    background: #f00;
}

But no luck.

Remove the space between li and .current .

#menu li .current means "any element of class .current inside a li inside #menu ."

#menu li.current means " li of class .current inside #menu ."

And yes, it's OK to add class="current" to the current menu item on each page.

Remove the space between li and .current .

#menu li.current{
    background: #f00;
}

When you're targeting an element with a specific class, the class should always come directly after the element. If not, you're targeting any child element of the element that has the specified class.

try this

http://jsfiddle.net/ePtFq/1/

OR used JS

 $(document).ready(function (e) {
            var page = top.location.toString().split('/');
            $('#menu').find('a[href="' + page[page.length - 1].toString() + '"]').closest('li').addClass('current');
        });

Use this simple Javascript

function LoadCurrentMenu()
    {
        var str=location.href.toLowerCase();
        $("#menu li a").each(function() {
            if (str.indexOf($(this).attr("href").toLowerCase()) > -1) {
                $("li.current").removeClass("current");
                $(this).parent().addClass("current");
            }
        });
        $("li.current").parents().each(function(){
            if ($(this).is("li")){
                $(this).addClass("current");
            }
        });
     }

and call this function on body load event like below

<body onload="LoadCurrentMenu();">
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM