停止由$ animate.addClass

时间:2016-06-09 06:38:16

标签: javascript jquery css angularjs animation

有没有办法停止$ animate.addClass启动的动画?



angular.module("app", []);
angular.module("app").directive("stopAnimation", function($animate) {
  return {
    link: function(scope, element) {
      setTimeout(function() {
        
        // Start animation
        scope.$applyAsync(function() {
          var promise = $animate.addClass(element, "is-visible");
          
          // Stop animation
          setTimeout(function() {
            $animate.cancel(promise);
          }, 100);
        });
      });
    }
  };
});

.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background: red;
  transform: translateY(-100%);
}

.header.is-visible {
  transform: translateY(0);
}

.header.is-visible {
  transition: transform 3s;
}

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="header" stop-animation></div>
</body>
</html>
&#13;
&#13;
&#13;

在此演示中,动画应在100ms后停止,因为承诺已取消。但是,它正常完成。我想要实现的是停止动画并使其立即跳转到它的最终状态。

2 个答案:

答案 0 :(得分:1)

也许您可以将.is-visible的过渡更改为无。在setTimeout函数之后,您可以再次添加它。

// Stop animation
setTimeout(function() {
        $(".is-visible").css("transition","none");
      }, 100);
 }

答案 1 :(得分:1)

如果我理解正确,您可以使用$animate.setClass。移除您的is-visible课程并添加没有过渡的新css。

&#13;
&#13;
angular.module("app", []);
angular.module("app").directive("stopAnimation", function($animate) {
  return {
    link: function(scope, element) {
      setTimeout(function() {
        
        scope.forceCancel = function(){
          $animate.setClass(element, "is-visible-stopped","is-visible");
        }
        // Start animation
        scope.$applyAsync(function() {
          var promise = $animate.addClass(element, "is-visible");
          
          // Stop animation
          setTimeout(function() {
            $animate.cancel(promise);
          }, 100);
        });
      });
    }
  };
});
&#13;
.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background: red;
  transform: translateY(-100%);
}

.header.is-visible {
  transform: translateY(0);
}

.header.is-visible {
  transition: transform 3s;
}

.header.is-visible-stopped {
  transform: translateY(0);
}
&#13;
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="header" stop-animation> <button style="margin-top:60px" ng-click="forceCancel()"> Cancel</button></div>
</body>
</html>
&#13;
&#13;
&#13;