javascript - AngularJS - CSS animations are only working one way -
i'm trying animate element height: 20px
height: 0
, not working. however, transition 0 20 work. i'm using angular add/remove items array:
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 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>
relevant css:
.visible { height: 20px; transition: height 0.2s linear; } .hidden { height: 0; overflow: hidden; transition: height 0.2s linear; }
full code:
here order in events occur:
- the element appended class of
hidden
- the class subsequently changed
visible
- then reflow/paint event occurs , css updated visually
in doing so, aren't seeing transition when element appended because repaint event doesn't occur until class visible
.
one solution append element both classes , remove visible
class after slight 10ms timeout. in doing so, reflow event occur , transition take effect expected.
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 = ''; }
then modify css following:
.visible { height: 20px; transition: height 1s linear; overflow: hidden; } .hidden { height: 0; }
Comments
Post a Comment