开发者

Marking parent item as active when on child page

开发者 https://www.devze.com 2023-03-02 17:55 出处:网络
I have a navigation bar consisting of LI elements for the parent level. Each section which contains child pages are embedded with another unordered list. When viewing the page of a child element, the

I have a navigation bar consisting of LI elements for the parent level. Each section which contains child pages are embedded with another unordered list. When viewing the page of a child element, the child LI gets the class 'active', bu开发者_JS百科t the parent does not. How do I assign the active class to the parent item as well with jQuery or CSS?


Use closest() it selects the closest parent matching the selector. So if your child element is several elements deep it will still find the right parent as opposed to .parent() which only grabs the immediate parent or .parents() which grabs all the parents up until your selector.

$('.child').closest('.parent').addClass('active');


It's still beta, so I don't know if you're using jQuery UI Menu already (or if you're not using any JavaScript at all yet)? However, with jQuery UI Menu, something like this:

function activate_parent(e, u){
    $("#ui-active-menuitem").parents("li").filter(function(i){
        return !($(this).closest("ul").hasClass(".ui-menu-flyout"));
    }).find("a").addClass(".ui-state-hover");
    return;
}

$("#menu").menu({
    'focus': activate_parent
});
0

精彩评论

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