首页 > 解决方案 > 如何在 angularjs 中使用 ng-if 向下滑动和向上滑动元素?

问题描述

我有以下组件。

<my-section
    ng-if="$ctrl.playerId"></my-section>

这个 playerId 是动态的。当它不存在时,我希望这个元素向上滑动。当它发生时 - 我希望它向下滑动。我怎样才能做到这一点?

标签: angularjscss

解决方案


您可以引入 ngAnimate 模块并利用某些在 DOM 更改时应用的 CSS 类。

对于,ng-if你会特别想看看。.ng-enter.ng-leave

下面是一个示例来演示。

不要忘记查看有关动画的官方文档

angular
  .module('app', ['ngAnimate'])
  .controller('ctrl', function ($scope) {
    $scope.playerId = false;
  })
  .component('mySection', {
    template: '<pre>...</pre>',
  });
my-section {
  background: silver;
  display: block;
  height: 100px;
}
my-section.ng-enter,
my-section.ng-leave {
  transition: all ease-out .3s;
}
my-section.ng-enter,
my-section.ng-leave.ng-leave-active {
  height: 0;
}
my-section.ng-leave,
my-section.ng-enter.ng-enter-active {
  height: 100px;
}
<div ng-app="app" ng-controller="ctrl as $ctrl">
  <input type="checkbox" ng-model="$ctrl.playerId">
  <my-section ng-if="$ctrl.playerId"><my-section>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-animate.min.js"></script>


推荐阅读