简体   繁体   中英

jquery, add active class to links

Hi i'm working on a off canvas menu and I want to add a class to highlight active menu item but the jquery code I'm currently working with does not seem to add the class to the active link. I tried all potential solutions I came across in the web and nothing seem to work. Any suggestions, ideas, resources?

<nav class="site-menu">
       <div class="menu-list"> 
        <ul>
            <li><a href="portfolio.php">portfolio</a></li>
            <li><a href="projects.php">projects</a></li>
            <li><a href="process.php">process</a></li>
            <li><a href="blog.php">blog</a></li>
            <li><a href="contact.php">contact</a></li>
        </ul>
        </div>
    </nav>

css

 .site-menu ul {
    list-style: none;
    padding: 20px;
    margin: 0;
}

.site-menu ul li a {
    display: block;
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: #7f7f7f;
    background: transparent;
    text-decoration:none;
}

.menu-list{
    position: absolute;
    top: 80px;
    margin-left: 10px;
    font-family: 'Open Sans',     sans-serif;
    font-weight: 400;
    text-transform: uppercase;
    letter-spacing: 2px; 
    text-align: left;
     }

.active {
    color:#fff;
}

script

var selector = ".site-menu li";

$(selector).click(function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

You need to make CSS selector more specific:

.site-menu ul li.active a {
    color: #fff;
}

Otherwise the rule .site-menu ul li a has higher precedence.

Read on the subject: CSS Specificity: Things You Should Know .

Demo: http://jsfiddle.net/6ck1Lg0w/

Try this:

var selector = ".site-menu li";

selector.click(function(){
    selector.removeClass('active');
    $(this).addClass('active');
});

您必须将选择器更改为以下选择器:

var selector = ".site-menu ul li a";

When you load a new page the javascript changes will be lost. But you can check what page is active when the page is loaded like this:

JS

(function($){
    $('.site-menu li a').each(function(){
        if( $(this).attr('href') == window.location.pathname ) $(this).addClass('active');
    })
})

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