简体   繁体   中英

Changing background color for selected list <li>…</li>

Once we click on any <li> in the accordion, it should be selected (applying some background color) until we will click another <li> . I tried following code, can anyone help me?

 $("#accordian h3").click(function() {
      var txt = $(this).text();
      //alert(txt);
      //slide up all the link lists
      $("#accordian ul ul").slideUp();
      //$(this).css('border-left','18px solid #ff1800');
      //slide down the link list below the h3 clicked - only if its closed
      if(!$(this).next().is(":visible")) {
           $(this).next().slideDown();
      }
     })
 });

 /*  $("li").click(function(){
      $(this).css('background','orange');
 }); */

Here is jsFiddle

Thanks

Try this.

$("li").click(function(){
    $(this).addClass('orange').siblings('li').removeClass('orange');
});  

Update Fiddle

Working solution!

jQuery:

$("#accordian ul li ul li").click(function(){
        $('#accordian ul li ul li').removeClass('red');
        $(this).addClass('red');
     });

CSS:

.red, .red:hover, .red:active {
    background: #f00 !important;
}

And CSS Modification:

/*hover effect on links*/
#accordian ul ul li:hover {
    background: #003545;
    border-left: 5px solid lightgreen;
}

http://jsfiddle.net/J5Hd4/1/

$("#accordian h3").click(function(){
        var txt = $(this).text();   
    $('#accordian h3').css('background', '#003040'); // this gives the default background you have to all the h3's
        //slide up all the link lists
        $("#accordian ul ul").slideUp();
    $(this).css('background','orange');  // this gives the new background only to the one that was clicked on
        if(!$(this).next().is(":visible"))
        {
            $(this).next().slideDown();
        }
     });

You can do:

$("#accordian h3").click(function () {
    var txt = $(this).text();
    //slide up all the link lists
    $("#accordian ul ul").slideUp();
    if (!$(this).next().is(":visible")) {
        $(this).next().slideDown();
    }
    $('#accordian li.active').removeClass('active');
    $(this).closest('li').addClass('active');
});

Updated Fiddle

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