【问题标题】:Angular animate not working correctly on first run when element is initially hidden最初隐藏元素时,角度动画在首次运行时无法正常工作
【发布时间】:2016-02-15 16:50:58
【问题描述】:

我在我的 Angular 应用程序上连接了一个状态栏,目的是当向服务器发出请求时,状态栏将显示响应消息,将有一个背景颜色来表示成功或错误,如果成功几秒钟后隐藏。

我看到的是,在加载页面后第一次运行此逻辑时,动画不会运行(淡入和定时淡出都无法运行),但前提是状态栏元素最初是隐藏的,如果我在页面加载时将 ng-show 变量设置为 true,所有动画都会按预期工作。

我确实通过 chrome 的开发人员工具检查了源代码,在第一次运行期间,在动画应该完成后,div 具有这些类 alert-bar ng-hide-remove ng-hide-remove-active alert-bar-success ng-animate ng-hide。当动画确实起作用时,唯一存在的类是alert-bar alert-bar-success ng-animate ng-hide

HTML:

<div class="alert-bar" ng-show="response.show"  ng-class="(response.result == true) ? 'alert-bar-success' : 'alert-bar-danger'">
    <div class="container">
        <label>Message: {{response.message}}</label>
    </div>
</div>

CSS:

.alert-bar {
    width: 100%;
    margin-top: -20px;
    margin-bottom: 20px;
}

.alert-bar-success {
    background-color: #5cb85c;
    border-color: #4cae4c;
    color: #ffffff;
}

.alert-bar-danger {
    color: #ffffff;
    background-color: #d9534f;
    border-color: #d43f3a;
}

.alert-bar.ng-hide-add, .alert-bar.ng-hide-remove {
  -webkit-transition:all linear 0.3s;
  -moz-transition:all linear 0.3s;
  -o-transition:all linear 0.3s;
  transition:all linear 0.3s;
  display:block!important;
}

.alert-bar.ng-hide-add.ng-hide-add-active,
.alert-bar.ng-hide-remove {
  opacity:0;
}

.alert-bar.ng-hide-add,
.alert-bar.ng-hide-remove.ng-hide-remove-active {
  opacity:1;
}

控制器:

controllers.controller("AppController", ['$scope', '$timeout', function($scope, $timeout) {
    $scope.response = {};

    $scope.response.received = function(message, result) {
        $scope.response.message = message;
        $scope.response.result = result;
        $scope.response.show = true;
        if (result == true) {
            $timeout(function () {
                $scope.response.show = false;
            }, 4000);
        }
    };
}]);

【问题讨论】:

    标签: angularjs ng-animate


    【解决方案1】:

    这是由于应用于ng-classng-hide 指令的动画代码之间的相互作用造成的。我使这样的事情工作的唯一方法是使用单独的 &lt;div&gt; 元素,这些元素有条件地显示/隐藏,但具有静态类。

    这是一个 plunkr,它演示了将上述内容拆分为两个 &lt;div&gt; 元素,以便为问题中的问题创建一个工作示例:

    http://plnkr.co/edit/PFNGkOLKvs8Gx9h1T6Yk?p=preview

    或者,您可以完全放弃使用ng-hide/ng-show,而只使用ng-class

    编辑:请参阅 http://plnkr.co/edit/JiLPc6cqiLHR21c64cCy?p=preview 以获取专门使用 ng-class 的版本。

    【讨论】:

    • 太棒了,我可以忍受使用 2 个 div。明天锁定时间结束时,我将奖励赏金。
    • 很高兴为您提供帮助!我继续创建了一个新的 plunkr,它演示了一种方法,它可以通过单个 divng-class 来实现,而无需 ng-hideplnkr.co/edit/JiLPc6cqiLHR21c64cCy?p=preview
    【解决方案2】:

    您不需要使用两个 div。我想最简单的解决方案只是将动画 css 放入类“ng-hide-add-active”,而不是放入“ng-hide-add”。如下:

    .page-ready-animate.ng-hide-add-active {
      -webkit-animation: 0.5s fadeOutDown;
      animation: 0.5s fadeOutDown;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      相关资源
      最近更新 更多