简体   繁体   中英

After adding a “current” class to an active item in a menu using jQuery, how can css changes be made to the container of the item?

I have added an "active" class to the current item in a menu bar and have implemented a Smooth Scroll feature to it as well. ( http://jsfiddle.net/T98VG/ )

I want the background color of the item to change in the menu bar but this doesn't seem to be working properly. So far, the background color of the link in the menu bar changes, not the container the link is in. How can I implement this?

jQuery code used to add "active" state to current item (this works fine):

$(document).ready(function () {
$(document).on("scroll", onScroll);

//smoothscroll
$('#nav a[href^="#"]').on('click', function (e) {
    e.preventDefault();
    $(document).off("scroll");

    $('#nav a').each(function () {
        $(this).removeClass('current');
    });
    $(this).addClass('current');

    var target = this.hash,
        menu = target;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-0
    }, 1000, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
});

});

function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#nav a').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
        $('#nav a').removeClass("current");
        currLink.addClass("current");
    }
    else{
        currLink.removeClass("current");
    }
});

}

Here's a JSFiddle with the code I have so far and the problem ( http://jsfiddle.net/T98VG/ ). In the menu bar with 4 items: #1, #2, #3 and #4, only the background color of the active link gets highlighted. I'd like the box "nav li" to be filled with the color as well.

I'm new to coding so all help is welcome. Thank you!

You can use the parent() call on each link, and add the current class to the parent of the links (the <li> 's) instead of the links themselves.

See the updated JSFiddle

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