jquery - 如何使用 jQuery 在第二次单击时反转 CSS 动画

标签 jquery css function animation reverse

我制作了以下菜单图标 CSS 动画,当我点击它时会触发它。当我使用 jQuery 第二次单击它时,我想让它反向动画。

#path1 {
  stroke-dasharray: 33px;
  stroke-dashoffset: 33px;
  animation: line 1.5s linear forwards;
  animation-play-state: paused;
}

@keyframes line {
  100% {
    stroke-dashoffset: -15.5;
  }
}

#halfLineLeft {
  transform-origin: 1% 50%;
  animation: shrinkleft 1s linear forwards;
  animation-play-state: paused;
}

 #halfLineRight {
  transform-origin: 100% 1%;
  animation: shrinkleft 1s linear forwards;
  animation-play-state: paused;
}

@keyframes shrinkleft {
  100% {
    transform: scale(0,1);
  }
}
svg {
  transform: translate(350px, 200px);
}

这是我目前使用的 jQuery...

$("svg").click(
  function(){
     $("#path1, #halfLineLeft, #halfLineRight").css("animation-play-state", "running");
  }
 );

当我第二次单击 SVG 图标时,我似乎无法弄清楚如何使它反向动画。我没有任何运气地尝试了这段代码:

$("svg").click(
  function(){
     $("#path1, #halfLineLeft, #halfLineRight").css("animation-state", "running"),
     $("#path1, #halfLineLeft, #halfLineRight").css("animation-direction", "reverse");
  }
 );

这是带有现场动画的codepen链接:

http://codepen.io/anon/pen/xEORBJ

最佳答案

我不知道这是否是最有效的方法,但添加反向关键帧和切换类似乎可行。

codepen example

#path1.active {
  animation: line 1.5s forwards;
}

#path1.inactive {
  stroke-dashoffset: -15.5;
  animation: unline 1s linear forwards;
}

#halfLineLeft.active {
  animation: shrinkleft 1s linear forwards;
}

#halfLineRight.active {
  animation: shrinkleft 1s linear forwards;
}

#halfLineLeft.inactive {
  transform: scale(0, 1);
  animation: unshrinkleft 1s linear forwards;
}

#halfLineRight.inactive {
  transform: scale(0, 1);
  animation: unshrinkleft 1s linear forwards;
}

#path1 {
  stroke-dasharray: 33px;
  stroke-dashoffset: 33px;
}

@keyframes line {
  100% {
    stroke-dashoffset: -15.5;
  }
}

@keyframes unline {
  100% {
    stroke-dashoffset: 33px;
  }
}

@keyframes shrinkleft {
  100% {
    transform: scale(0, 1);
  }
}

@keyframes unshrinkleft {
  100% {
    transform: scale(1, 1);
  }
}

#halfLineLeft {
  transform-origin: 1% 50%;
}

#halfLineRight {
  transform-origin: 100% 1%;
}

svg {
  transform: translate(50px, 50px);
}

$("svg").click(
  function() {
    $("#path1, #halfLineLeft, #halfLineRight").toggleClass("active");

    if (!$("#path1, #halfLineLeft, #halfLineRight").hasClass("active")) {

      $("#path1, #halfLineLeft, #halfLineRight").addClass("inactive");

    } else {
      $("#path1, #halfLineLeft, #halfLineRight").removeClass("inactive");
    }
  }
);

关于jquery - 如何使用 jQuery 在第二次单击时反转 CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39537494/

相关文章:

javascript - 新建div添加类名并修改样式

r - 在R中的数据点之上绘制函数

javascript - Bootstrap datetimepicker 获取时间

jquery - 切换整个 jQuery jstree

javascript - 二级全屏叠加导航

java - 对于不返回内容的方法是否强制使用 void ?

python - 输入数字500以下的最大幂

javascript - 如何使用外部源覆盖包含 iframe 的 div?

css - 悬停在链接上时如何将图像设置为光标

css - 如何创建一个使用 BootStrap 的 WordPress 主题?