动效概述
- Angular动效遵守的规范:https//w3c.github.io/web-animations/ (这个是w3c的规范,目前还是处于草案状态,可以看出Angular还是走在听前面的,哈哈)
- 浏览器的支持情况:http://caniuse.com/#search=web-animation,从这边看到目前浏览器对web-animation的支持情况还是很差的,只有chrome和firefox支持还不错,IE/Edge/Safari这几个是完全不支持,然后。然后安卓的4.x版本不支持,高版本支持,iOS的Safari是不支持的。
- Animation包不在angular/core里面,需要进行独立import:
import {BrowserAnimationsModule} from '@angular/platform-browser';
Angular动效的构成
主要是由‘状态’和‘状态变换’构成
写一个自定义的动画
首先看看代码结构:
其次,直接看代码了,写法具体看注释即可:
动画的ts代码:
// 首先要从angular/animations里面import这么写东西
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
// 然后使用trigger方法定义一个名字叫'flyIn'的动画效果
export const flyIn = trigger('flyIn', [
// 在组件从void(不可见)状态变到*(任意)状态的过程中,时间持续三秒,在这三秒中有这么几个关键帧(keyframe),对应的样式分别是这样的...
transition('void => *', [
animate(3000, keyframes([
style({ opacity: 0, transform: 'translateX(-100%)', offset: 0 }),
style({ opacity: 1, transform: 'translateX(25px)', offset: 0.3 }),
style({ opacity: 1, transform: 'translateX(0)', offset: 1.0 })
]))
]),
// 在组件从*(任意)状态转换到void(不可见)状态时,又是怎么怎么样
transition('* => void', [
animate(300, keyframes([
style({ opacity: 1, transform: 'translateX(0)', offset: 0 }),
style({ opacity: 1, transform: 'translateX(-25px)', offset: 0.7 }),
style({ opacity: 0, transform: 'translateX(100%)', offset: 1.0 })
]))
])
]);
随后,组件是怎样使用这个自定义动画的呢?
首先,在html模板代码中使用[@flyIn]=”的方式将动画绑定到一个属性上。
然后在组件类代码中声明对应的属性就可以了。
<!--使用[@flyIn]='state'将动画绑定到state属性-->
<div class="panel panel-primary" [@flyIn]="state">
<div class="panel-heading">飞入效果</div>
<div class="panel-body">
飞入效果
</div>
</div>
ts中声明state属性:
import { Component, OnInit } from '@angular/core';
// 首先,导入flyIn这个自定义动画
import { flyIn } from '../animations/fly-in';
@Component({
selector: 'app-test-fly-in',
templateUrl: './test-fly-in.component.html',
styleUrls: ['./test-fly-in.component.css'],
// 然后在@Component装饰器中,添加animations配置项,告诉组件要使用这个动画
animations:[flyIn]
})
export class TestFlyInComponent implements OnInit {
// 最后,声明state这个属性,以绑定对应的动画
state:string;
constructor() { }
ngOnInit() {
}
}