javascript - 带动画的 Angular 显示/隐藏

标签 javascript jquery html css angularjs

我试图淡出一个 div,然后显示一个新的 div,但我的代码被破坏了。我该如何解决?淡出动画有效,但 showManagement div 没有出现。

HTML

<div ng-hide="hidden" ng-class="{fade: startFade}">
    <p>this is start content that should be faded</p>
</div>
<div class="showManagement" ng-show="showManagement">
    <p>this is the new content to be displayed once the fade is complete.</p>
</div>

JS

$scope.getManagement = function () {

    $scope.startFade = true;

    $timeout(function(){
        $scope.hidden = true;
    }, 2000);

    // this is the part that doesn't display
    $scope.showManagement = true;
 };

CSS

.fade{
    transition: opacity 3s;
    opacity: 0;
}

最佳答案

因为您没有提供 Controller ,也没有显示调用函数的位置 getManagement() ,我假设您希望在 Angular 加载后 2 秒内显示所有淡出淡入事件。

这是一个 example on CodePen了解如何通过您的方法实现目标。

代码如下:

HTML

<body ng-app="myApp">
  <div class="wrapper" ng-controller="MainCtrl">
    <div ng-class="{fade: startFade}">
        <p>this is start content that should be faded</p>
    </div>
    <div ng-class="{hideManagement: hideManagement, showManagement: showManagement}">
        <p>this is the new content to be displayed once the fade is complete.</p>
    </div>
  </div>
</body>

CSS

.fade{
    transition: opacity 3s;
    opacity: 0;
}

.hideManagement {
  opacity: 0;
}

.showManagement {
    transition: opacity 3s 3s;
    opacity: 1;
}

JS

angular
  .module('myApp', [])
  .controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    $scope.startFade = false;
    $scope.showManagement = false;
    $scope.hideManagement = true;

    $timeout(function(){
      $scope.startFade = true;
      $scope.showManagement = true;
      $scope.hideManagement = false;
    }, 2000);
  }]);

需要注意的几点:

  1. 你不能为你的 display: none; 设置动画和 display: block;使用 CSS3 过渡。这就是为什么 ng-hide 的原因在你的.showManagement不显示过渡效果。你应该继续使用 opacity实现这个目标,就像您在 ng-class="{fade: startFade}" 中所做的一样
  2. 在您的 Angular Controller 开始时初始化您的状态。在您提供的示例中,设置 $scope.showManagement 的方式有点令人困惑。 , $scope.hidden , 和 $scope.startFade .一旦像我提供的示例那样设置了初始状态,就会更清楚应该在函数中更改哪种状态,无论它是在 $timeout 中。回调或其他事件触发的一些其他功能
  3. 制作.showManagement在第一个 <div> 之后淡入完成它的淡出效果,你可以在 css transition 中设置延迟。

如果您正在制作更复杂的动画,您应该尝试利用 ngAnimate服务。使用 ngAnimate,您可以摆脱那些 ng-class在此示例中,只需将您的动画规则与 .ng-enter 绑定(bind)即可, .ng-enter-active , .ng-hide , .ng-hide-active ,它们会被 Angular 自动绑定(bind)到你的元素上。这是 official documentation对于 ngAnimate .

关于javascript - 带动画的 Angular 显示/隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778995/

相关文章:

javascript - 将列样式应用于表体元素

Firefox 7 中的 Javascript 匿名函数

javascript - 复选框树

jQuery - 从表的最后一行获取输入字段值?

javascript - 将值附加到 URL 搜索参数

javascript - 单击其他输入时在输入上触发 jquery 函数

javascript - Jquery 可以工作,但只能工作一会儿

javascript - 使用 Bootstrap 模式的 Ajax 加载

html - 溢出隐藏隐藏位置绝对 block 。如果 Position Absolute block 在父 block 之外,则它会消失

php - 我的网站无法识别运行 ghost css 脚本的 css 文件