2

I have this menu

            <ul id="menu" class="clearfix">
                <li>
                    <a href="">Product 1</a>
                </li>
                <li>
                    <a href="">Product 2</a>
                </li>
                <li>
                    <a href="">Product 3</a>
                </li>
                <li class="last">
                    <a href="">Product 4</a>
                </li>
            </ul>

I want to make this effect. when you enter the page the text color of the menu items are white. If you click on one item it becomes active (keeping the white color text) and all the other items change it's color to gray, also when you hover over one the affected items are all the others.

I have tried with the .addClass but I have only managed to add the active class to the current item, but not change the others that aren´t active after the first click.

Anyone know the best jquery approach to this?

4

4 回答 4

2
$("#menu li").hover(function() {
    $(this).removeClass('grey').siblings().addClass('grey');
}, function() {
    $(this).addClass('grey').siblings('.active').removeClass('grey');
    //
}).on('click', function() {
    $(this).removeClass('grey').addClass('active').siblings().addClass('grey').removeClass('active')
});​

http://jsfiddle.net/y7Cn5/

于 2012-11-14T18:36:04.450 回答
1

也许是这样的:

更新,具有悬停功能

jsFiddle

$("#menu > li").on("click", function(e) {
    e.stopPropagation();
    $(".active").removeClass("active");
    $(this).removeClass("non-active").addClass("active").siblings().addClass("non-active");
})
.hover(function(e) {
    $(".non-hover").removeClass("non-hover");
    $(this).addClass("hover").siblings().addClass("non-hover");
}, function(e) {
    $(".hover, .non-hover").removeClass("hover non-hover");
})

如果这不能回答问题,那么问题就没有被理解,需要重新措辞,这就是问题中所问的一切

于 2012-11-14T18:31:02.277 回答
0

Here you go (siblings) 选择同一节点中的所有 OTHER 项

$("#menu li").click(function(){
  $(this).addClass("active").css("color","white")
  $(this).siblings().css("color","gray")
})
于 2012-11-14T18:27:31.087 回答
0

尝试

$("#menu > li").hover( function( ) {
    $(this).removeClass("hovered").siblings().addClass("hovered");
}, function( ) {
    $(this).addClass("hovered");
});

$("#menu > li").click( function( ) {
    $(this).addClass("active").siblings().removeClass("active");
});
于 2012-11-14T18:44:55.937 回答