Animate Font Awesome Chevron图标旋转崩溃/扩展

时间:2018-04-20 21:11:18

标签: javascript jquery css bootstrap-4 font-awesome

当隐藏或显示可折叠内容时,我希望我的图标能够明显旋转。

这是我的功能,它添加一个V形图标并旋转它:

$('[data-toggle="collapse"]').each(function(){
    var collapser = $(this);
    // TODO: 'collapsed' class should be added manually if the toggled element is not shown
    // i.e., if you remove 'show' class, add 'collapsed' class, or this function is confused
    collapser.append('<span style="float:right;"><i class="fa fa-chevron-right'
            +(collapser.hasClass('collapsed')?'':' fa-rotate-90')
            +'"/></span>');
    collapser.on('click', function(){
        var chevron = collapser.find('.fa-chevron-right'); // it was replaced with svg
        if (collapser.hasClass('collapsed')) {
            chevron.addClass('fa-rotate-90');
        } else {
            chevron.removeClass('fa-rotate-90');
        }            
    });
});

我想添加更平滑的过渡,但更好的是没有css,只修改此代码。 CSS对我来说太麻烦了

欢迎任何其他对此代码的批评

1 个答案:

答案 0 :(得分:2)

To make your animations smoother you can make use of the css transition property.

Simply add this code to your css:

.fa-chevron-right {
  -webkit-transition: transform .4s; /* Safari */
  transition: transform .4s;
}

or you can add the CSS directly with jQuery by modifying your code appending element this (not recommendet):

 collapser.append('<span style="float:right;"><i style="transition: transform .4s;" class="fa fa-chevron-right'
    +(collapser.hasClass('collapsed')?'':' fa-rotate-90')
    +'"/></span>');

You can learn more about CSS transitions here: https://www.w3schools.com/css/css3_transitions.asp

In general, I recommend you to learn CSS and create your animations whenever possible with it. You will see it's much easier and you get ways better performance.