Active Menu Highlight CSS

后端 未结 11 896
孤独总比滥情好
孤独总比滥情好 2020-11-29 00:54

I want to highlight the current menu you have click. I\'m using CSS, but it is now working.

here is my css code:

#sub-header ul li:hover{ background-         


        
11条回答
  •  一生所求
    2020-11-29 01:47

    First, give all your links a unique id and make a css class called active:

    
    

    CSS:

    .active {
        font-weight: bold;
    }
    

    Jquery version:

    function setActiveLink(setActive){
        if ($("a").hasClass('active'))
            $("a").removeClass('active');
        if (setActive)
            $("#"+setActive).addClass('active');
    }
    
    $(function() {
        $("a").click(function() {
            setActiveLink(this.id);
        });
    });
    

    Vanilla javascript version:

    In order to prevent selecting too many links with document.querySelectorAll, give the parent element an id called menuLinks. Add an onClick handler on the links.

    
    

    Code:

    function setActiveLink(setActive){
        var links = document.querySelectorAll("#menuLinks a");
        Array.prototype.map.call(links, function(e) {
            e.className = "";
            if (e.id == setActive)
                e.className = "active";
        })
    }
    

提交回复
热议问题