CSS, JQuery: Animated transform from 3 lines menu

2019-04-15 16:51发布

问题:

I am wondering how to create an animation that would transform a 3 lined menu into a cross. The structure of the following buttons is sketched on the picture above. The 3 lines are created using 3 spans and the cross is created using before and after elements and rotate transition. Now I only use jquery to toggle class that changes the look of the button, but I would like to achieve some nice, animated effect such as

  1. one line of the 3-lined menu dissapears
  2. the rest 2 lines rotates and creates the cross

and of course, inverse process when going from cross to 3-lined menu.

How to achieve that?

Here's the fiddle http://jsfiddle.net/eaNEE/65/

HTML:

  <div id="menu-toggle-btn">
    <span></span>
    <span></span>
    <span></span>
  </div>

SASS:

  #menu-toggle-btn {
    margin: 15px 10px;
    width: 30px;
    cursor: pointer;
    left: 15px;
    z-index: 10;

    &.js-transform {
        span {
            display: none !important;
        }

        &:before, &:after {
            content: "";
            width: 4px;
            height: 25px;
            display: block;
            background: #1d1d1b;
        }

        &:before {
          -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
        }
        &:after {
                      -ms-transform: rotate(-45deg); /* IE 9 */
    -webkit-transform: rotate(-45deg); /* Chrome, Safari, Opera */
    transform: rotate(-45deg);
            margin-top: -25px;
        }

    }

    span {
        display: block;
        background: #1d1d1b;
        height: 4px;
        width: 30px;
        margin: 5px;
    }
}

回答1:

Here's the fiddle http://jsfiddle.net/uwozd36q/1/

HTML:

<div class="menu-toggle-btn">
    <span></span>
    <span></span>
    <span></span>
</div>

SASS:

.menu-toggle-btn{
    margin: 15px;
    cursor: pointer;
    width: 30px;
    height: 30px;

    span{
        background: #1d1d1b;
        display: block;
        width: 30px;
        height: 4px;
        border-radius: 5px;
        margin-bottom: 5px;
        -webkit-transition: all 0.5s linear;
        transition: all 0.3s linear;
    }
    &.open{
        span{
            &:nth-child(1),
            &:nth-child(3){
                transform: translate(0px, 13px) rotate(-45deg) scalex(1.3);
                margin: 0;
            }
            &:nth-child(2){
                height: 0;
                margin: 0;
            }
            &:nth-child(3){
                transform: translate(0px, 9px) rotate(45deg) scalex(1.3);               
            }
        }
    }
}

jQuery:

$(".menu-toggle-btn").click(function() {
    $(this).toggleClass("open");
});