使用jquery在手风琴上切换图标

时间:2013-11-27 10:51:45

标签: jquery

我使用html css和jQuery构建了一个手风琴。除图标外,它可以很好地显示标签是打开还是关闭。这是我的codepen

jQuery代码如下:

$('ul#accordion > li > a').click(function(e){
        var $this = $(this),
            accordionSpan = $('#accordion > li > a span');

         if ($this.attr('class') != 'active'){
            accordionSpan.removeClass();
            accordionSpan.addClass('icon-arrow-up-6');
            $('#accordion li ul').slideUp(200);
            $this.next().slideDown(200);
            $('#accordion li a').removeClass('active');
            $this.addClass('active');
            $this.children().addClass('icon-arrow-down-7');
         } else {
            $this.next().slideToggle(200);
            if($this.children().hasClass('icon-arrow-down-7')) {
                $this.children().removeClass('icon-arrow-down-7').addClass('icon-arrow-up-6');
            } else {
                $this.children().removeClass('icon-arrow-up-6').addClass('icon-arrow-down-7');
            }
         }
         e.preventDefault();
    });

关闭时我需要图标为'+',打开时我需要' - '。

2 个答案:

答案 0 :(得分:1)

试试这个

$('ul#accordion > li > a').click(function(e){
    var $this = $(this),
        accordionSpan = $('#accordion > li > a span');
      $this.addClass('active'); /// you miss this line
     if ($this.attr('class') != 'active'){
        accordionSpan.removeClass();
        accordionSpan.addClass('icon-arrow-up-6');
        $('#accordion li ul').slideUp(200);
        $this.next().slideDown(200);
        $('#accordion li a').removeClass('active');
        $this.addClass('active');
        $this.children().addClass('icon-arrow-down-7');
     } else {
        $this.next().slideToggle(200);
        if($this.children().hasClass('icon-arrow-down-7')) {
            $this.children().removeClass('icon-arrow-down-7').addClass('icon-arrow-up-6');
        } else {
            $this.children().removeClass('icon-arrow-up-6').addClass('icon-arrow-down-7');
        }
     }
     e.preventDefault();
});

答案 1 :(得分:0)

最佳方式: 例如,为两个图像添加类

$(document).ready(function(){
  $("button").click(function(){
    $(".one").toggle();
  });
});
</script>
</head>
<body>


<img class="one" src="">+</img>
<img class="one" src="" style="display:none">-</img>
<button>Toggle between hide() and show()</button>

现在将display:none添加到&#34; - &#34;图像意味着&#34; - &#34;首先隐藏图像,然后点击&#34; - &#34;将显示图像以代替&#34; +&#34;图像,

您可以使用

标签取代它,谢谢