繁体   English   中英

AngularJS-CSS动画仅以一种方式起作用

[英]AngularJS - CSS animations are only working one way

我正在尝试从height: 20pxheight: 0设置一个元素的动画,但是它不起作用。 但是,从0到20的过渡确实有效。 我正在使用angular从数组添加/删除项目:

 angular.module('app', []) .controller('ctl', ctl); ctl.$inject = ['$timeout']; function ctl($timeout) { var self = this; self.newItemText = ''; self.deleteItem = function(id) { self.items[id].class = 'hidden'; }; self.addItem = function() { var newItem = { id: self.items.length, class: 'hidden', text: self.newItemText }; self.items.push(newItem); self.items[self.items.length - 1].class = 'visible'; self.newItemText = ''; } self.items = [{ id: 0, class: 'visible', text: 'one' }, { id: 1, class: 'visible', text: 'two' }, { id: 2, class: 'visible', text: 'three' }, { id: 3, class: 'visible', text: 'one' }, { id: 4, class: 'visible', text: 'two' }, { id: 5, class: 'visible', text: 'three' }, { id: 6, class: 'visible', text: 'one' }, { id: 7, class: 'visible', text: 'two' }, { id: 8, class: 'visible', text: 'three' }, ]; }; 
 body { font-family: arial; } .text { display: inline-block; } .close { cursor: pointer; } .visible { height: 20px; transition: height 0.2s linear; } .hidden { height: 0; overflow: hidden; transition: height 0.2s linear; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <div ng-app='app' ng-controller='ctl as c'> <input ng-model='c.newItemText' /> <button ng-click='c.addItem()'> add </button> <div> <ul> <li ng-repeat='item in c.items' class='{{item.class}}'> <span class='text'>{{item.text}}</span> <span class='close' ng-click='c.deleteItem(item.id)'>x</span> </li> </ul> </div> </div> 

相关的CSS:

.visible {
  height: 20px;
  transition: height 0.2s linear;
}
.hidden {
  height: 0;
  overflow: hidden;
  transition: height 0.2s linear;
}

完整代码:

https://jsfiddle.net/1rqhLo83/

这是事件发生的顺序:

  • 元素附加了一个hidden
  • 随后将类更改为visible
  • 然后发生重排/绘制事件 ,并且以可视方式更新CSS

这样做时,在最初添加元素时不会看到过渡,因为只有在类已visible之前才发生repaint事件。

一种解决方案是在元素上同时添加两个类,然后在稍长的10ms超时后删除visible类。 这样做会发生回流事件,并且过渡将按预期生效。

更新示例

self.addItem = function() {
    var newItem = {
    id: self.items.length,
    class: 'visible hidden',
    text: self.newItemText
  };
  self.items.push(newItem);
  $timeout(function () {
    self.items[self.items.length - 1].class = 'visible';
  }, 10);
  self.newItemText = '';
}

然后将CSS修改为以下内容:

.visible {
  height: 20px;
  transition: height 1s linear;
  overflow: hidden;
}
.hidden {
  height: 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM