AngularJS - CSS 动画只能以一种方式工作

AngularJS - CSS animations are only working one way

本文关键字:一种 工作 方式 CSS 动画 AngularJS      更新时间:2023-09-26

我正在尝试将元素从height: 20px动画化到height: 0,但它不起作用。但是,从 0 到 20 的转换确实有效。我正在使用角度从数组中添加/删除项目:

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之前不会发生重绘事件。

一种解决方案是将元素与两个类一起附加,然后在轻微的 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;
}
相关文章: