简体   繁体   English

更改图标时如何向按钮添加 CSS3 动画

[英]How to add CSS3 animation to a button when its icon is changed

I am trying to have CSS transition for a button when the font-awesome icon inside the button changes ie using jQuery one icon is replaced with the other.当按钮内的字体很棒的图标发生变化时,我正在尝试为按钮设置 CSS 转换,即使用 jQuery 将一个图标替换为另一个。

To give a better understanding of this, here is my HTML:为了更好地理解这一点,这是我的 HTML:

     <button type="button" class="navbar-toggle pull-left" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <i class="fa fa-navicon fa-lg"></i>
     </button>  

The jQuery that replaces the icon:替换图标的jQuery:

$(".navbar-toggle").on("click", function () {
        $(this).toggleClass("active");
        $('body').toggleClass("navbar-is-active");
        $('.navbar-toggle i').toggleClass('fa-navicon');
        $('.navbar-toggle i').toggleClass('fa-remove');
    });

The CSS styles for the button and CSS transition:按钮和 CSS 过渡的 CSS 样式:

.navbar-toggle {
    width: 81px;
    height: 80px;
    background: #c4414f!important;
    border-radius: 0;
    border: 0 none;
    margin: 0;
    padding-left: 29px;
    z-index: 2000;
}

.navbar-default .navbar-toggle .icon-bar {
        background-color: #FFF;
        height: 3px;
        border-radius: 0;
    } 
    .navbar-toggle.active {
        -webkit-box-shadow:inset 1px 1px 1px 1px #000000;
        box-shadow: -1px 1px 1px 0px #333333;
    }

.navbar-toggle {
    color: #FFF;
    padding-left: 10px;
}
    .navbar-toggle i {
        font-size: 24px;
        -webkit-transition: all 0.5s;
        transition: all 0.5s;
    }

But the transition is not working on the button when the menu icon is changed to an 'X'.但是当菜单图标更改为“X”时,按钮上的转换不起作用。 What am I doing wrong?我究竟做错了什么? I have made a Fiddle:我做了一个小提琴:

https://jsfiddle.net/471L8dfd/ https://jsfiddle.net/471L8dfd/

As requested, an example of the type of transition i am looking to add to the nav button:根据要求,我希望添加到导航按钮的转换类型示例:

过渡示例

Using fadeOut and fadeIn functions would do the trick:使用fadeOutfadeIn函数可以解决这个问题:

 $(".navbar-toggle").on("click", function () {
     $(this).toggleClass("active");
     $('body').toggleClass("navbar-is-active");
     $('.navbar-toggle i').fadeOut(100, function(){
         $(this).toggleClass('fa-navicon');
     })
     $('.navbar-toggle i').toggleClass('fa-remove').fadeIn(150);
 });

https://jsfiddle.net/471L8dfd/3/ https://jsfiddle.net/471L8dfd/3/

Edit: Note that class is toggled after fadeOut is order to prevent popping of icons and that the first animation speed (at 100ms) belongs to current icon fadeOut and the second to the next icon fadeIn .编辑:请注意,在fadeOut之后切换类是为了防止弹出图标,并且第一个动画速度(100 毫秒)属于当前图标fadeOut ,第二个动画速度属于下一个图标fadeIn Your total animation speed is these two values combined (100+150 = 250ms)你的总动画速度是这两个值的组合(100+150 = 250ms)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM