在toggleClass

时间:2018-02-21 00:39:48

标签: jquery

我使用此代码切换字体真棒图标。切换正在工作,但我想在那里给一些动画。但动画无效。

HTML:

<header>
    <h4><i class="fa fa-bars" aria-hidden="true"></i></h4>
</header>

jQuery的:

$('header h4').click(function() {
        $("i", this).toggleClass("fa-bars fa-times", 1000);
    });

1 个答案:

答案 0 :(得分:1)

我假设你想要对你的图标产生淡入/淡出效果。

&#13;
&#13;
$('header h4').click(function(e) {
    //if the icon has the class fa-bars
    if ($("i", this).hasClass('fa-bars')) {

      //fade the icon element out
      $("i", this).fadeOut('fast', function() {
        // remove the element from the dom
        $(this).remove();
      });

      // create the new element, append it to the dom, hide it immediately, then fade it in
      $('<i class="fa fa-times"></i>').appendTo($(this)).hide().fadeIn('fast');

    } else { //otherwise the icon has the other class (fa-times)
    
      //fade the icon element out
      $("i", this).fadeOut('fast', function() {
        // remove the element from the dom
        $(this).remove();
      });

       // create the new element, append it to the dom, hide it immediately, then fade it in
      $('<i class="fa fa-bars"></i>').appendTo($(this)).hide().fadeIn('fast');
    }
  });
&#13;
.fa-bars, .fa-times {
    position: absolute;
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
	<h4><i class="fa fa-bars" aria-hidden="true"></i></h4>
</header>
&#13;
&#13;
&#13;