How to toggle font awesome icon on click?

2020-05-15 15:05发布

I am using font awesome 'plus' icon on expandable categories list items. When they are in expanded state i want to show a 'minus' sign'

HTML

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-fw"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li>
</ul>

Jquery

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
});

enter image description here

6条回答
Explosion°爆炸
2楼-- · 2020-05-15 15:36

You can toggle the class of the i element within the clicked anchor like

<i class="fa fa-plus-circle"></i>

then

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});

Demo: Fiddle

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-15 15:39

There is another solution you can try by using only the css here is the answer i posted in another post: jQuery Accordion change font awesome icon class on click

查看更多
一纸荒年 Trace。
4楼-- · 2020-05-15 15:44
<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li> </ul>

//Jquery

$(document).ready(function() {
    $('li').click(function() {
      $('i').toggleClass('fa-plus-square fa-minus-square');
    });
  }); 

JSFiddle

查看更多
老娘就宠你
5楼-- · 2020-05-15 15:47

You can change the code by using class definition for the i element:

<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>

Then you can switch the classes rapresenting the plus/minus state using toggleClass with multiple classes:

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});

Demo: http://jsfiddle.net/Zcn2u/

查看更多
啃猪蹄的小仙女
6楼-- · 2020-05-15 15:53

Generally and simply it works like this:

<script>
            $(document).ready(function () {
                $('i').click(function () {
                    $(this).toggleClass('fa-plus-square fa-minus-square');
                });
            });
</script>

查看更多
ゆ 、 Hurt°
7楼-- · 2020-05-15 16:00

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

查看更多
登录 后发表回答