简体   繁体   中英

How can I change the background of a selected li in jquery?

I have an unordered list with a bunch of list items. I am setting the background of the selected <li> in its click:

$(this).animate({
          backgroundColor: '#0000FF'
}, 'fast');

When I click another <li> , I want to change its backgroundColor property, but I want the rest of the <li> s to default back to another color. This way, it looks like I am changing the selected state.

You could simply do the following:

$(this).siblings("li").css("backgroundColor", "");

Example on jsfiddle

$('ul li').click(function() {
    $(this).animate({backgroundColor:"#0000ff"},'fast')
        .siblings().animate({backgroundColor:"#000000"},'fast'); // or whatever other color you want
});

I would use a mixe of classes and CSS transitions :

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

li{background:#fff; -webkit-transition:all 0.25s linear; -moz-transition:all 0.25s linear;}
li.active{background:#00f;}
$('li').each.click(function(){
 $(this).css("backgroundColor", "");

});

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