更改所选列表的背景颜色<li> ... </li>

时间:2014-02-28 09:18:59

标签: jquery

一旦我们点击手风琴中的任何<li>,就应该选择它(应用一些背景颜色),直到我们点击另一个<li>。我尝试过代码,有人可以帮帮我吗?

 $("#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');
 }); */

这是jsFiddle

由于

4 个答案:

答案 0 :(得分:1)

试试这个。

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

Update Fiddle

答案 1 :(得分:1)

<强> 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;
}

和CSS修改:

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

答案 2 :(得分:0)

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();
        }
     });

答案 3 :(得分:0)

你可以这样做:

$("#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