我正在尝试将元素从 height: 20px
动画到 height: 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;
}
完整代码:
最佳答案
以下是事件发生的顺序:
- 该元素附加了一个
hidden
类 - 该类随后更改为
visible
- 然后是 reflow/paint event发生并且 CSS 进行了视觉更新
这样做时,您在最初附加元素时不会看到转换,因为直到类已经可见
后才会发生重绘事件。
一种解决方案是向元素附加两个类,然后在 10 毫秒的轻微超时后删除 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;
}
关于javascript - AngularJS - CSS 动画仅以一种方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260882/