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 chang开发者_如何转开发ing 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", "");
});
精彩评论