【问题标题】:How can I remove a class when the animation has ended?动画结束后如何删除类?
【发布时间】:2015-10-08 19:12:03
【问题描述】:

请帮我解决这个问题。 我有一个名为“选项”的按钮,如果单击它,我想将“.green”类添加到它以启动动画。动画使按钮的背景变为绿色,并开始将其淡化为原始颜色。但是,如果动画完成,我希望自动删除该类。这是必要的,因为如果您第二次添加该类,它就不再起作用了。我不喜欢使用“超时”功能。我遇到了一点麻烦,不能每次都工作。

我在下面发布了一个指向我的代码的链接。

My Code

@keyframes correct {
  from { color:forestgreen; }
}

.green {
    -webkit-animation: correct 0.4s ease-out;
    -moz-animation: correct 0.4s ease-out;
}

【问题讨论】:

  • 建议阅读所有动画文档并查看在动画阶段使用的所有类,假设您在支持动画的众多指令中执行此操作。然后还有$animateapi

标签: javascript css angularjs animation


【解决方案1】:

我查看了您的答案,但也找到了更简单的答案来解决问题。 我用了一行jQuery来修复它:

$('#' + String(list.answers[list.x])).addClass('green').one('animationend', function(){$(this).removeClass('green')});

我只是想让你知道..

谢谢!

【讨论】:

    【解决方案2】:

    你可以定义一个可重用的组件来通知元素上的动画结束,如下所示:

    .directive("onAnimationEnd", ["$timeout", function($timeout){
      return {
        scope: {
          onAnimationEnd: "&"
        },
        link: function(scope, element, attributes){
          element.on("animationend", function(e){
            $timeout(funciton(){
              scope.onAnimationEnd({event: e});
            });
          });
        }
      };
    }]);
    

    在您的 HTML 中,使用自定义指令以及 ng-classng-click 指令,如下所示:

    <!-- the method `removeGreenClass` will be called at the end of animation -->
    <button ng-class="{green: started}" ng-click="animationStarted = true" on-animation-end="removeGreenClass(event)">
    

    然后通过如下更新控制器来定义removeGreenClass 方法:

    .controller("MainCtrl",function($scope){
      console.log("Main Controller says: Hello World");
        var home = this;
        home.opties = false;
    
        $scope.animationStarted = false; // initially false
    
        $scope.removeGreenClass = function(event){
            $scope.animationStarted = false;
        };
    });
    

    【讨论】:

      【解决方案3】:

      您可以在元素上侦听animationend 事件。 More in this article.

      基本上,假设button 是您的按钮元素:

      var handler = function() {
          button.removeEventListener("animationend", handler, false);
          // (Remove the class here)
      };
      button.addEventListener("animationend", handler, false);
      // (Add the class here)
      

      (...或 addEventListener 的 Angular 等效项。)您可能需要该事件名称上的供应商前缀,文章中的详细信息。

      我怀疑你会想要删除处理程序(如上所示),因为删除类当然会启动另一个动画。

      【讨论】:

      • 其实不需要这个。 angular ngAmimte 模块已经在内部使用许多基于阶段的不同类来完成所有这些工作。只需在 css 中使用这些类即可
      • @charlietfl:更好! (这是答案,不是评论。)
      • @charlietfl,我认为你实际上搞混了。 AngularJS 文档对 Angular Animal 这么说:*如果在元素中添加或删除 CSS 类,则可以在 CSS 类添加或删除完成之前在其间执行动画。”但是,OP 希望收到结束通知动画,而不是当.green 类被删除时。据我所知,AngularJS 目前不这样做。
      • @IgweKalu 有多种方法可以做到这一点,包括通过内部支持动画的指令以及整个$animate api
      • @charlietfl,我认为$animate 做不到。但如果可以,请通过回答问题来证明我错了,我会很高兴有机会学习。
      猜你喜欢
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 2015-06-01
      • 2020-05-11
      • 1970-01-01
      • 2020-04-28
      相关资源
      最近更新 更多