返回目录css
文章基于angular的练手项目。文章目录html
让咱们隆重介绍Angular动画。Angular是基于最新的Web Animations API,咱们使用动画触发器(animation triggers)来定义一系列状态和变换属性。咱们也能够用CSS样式来改写实现咱们想要的效果
主要的原则是开始和结尾的动画样式由咱们自定义,中间变换的计算过程交给工具自己
固然,能够经过设置时间来设置中间动画,好比1s,1.2s,200ms。其余的就是你们熟悉的CSS动画的速度属性好比ease、liner和ease-in-out。
而Angular 4.2以上的版本里咱们能够用顺序(sequence)和组合(group)来让动画一个接一个执行仍是同时执行;查询(query)能够操做子元素而交错(stagger)能够创造一个很棒的连锁效果。
这些事件将触发一个动画:
向或者从视图里装载或者卸载一个元素
改变已绑定触发器的状态 好比:[@routerTransition]="home"
在路由转换的先后关系中,要注意,组件正在被移除并做为导航的一部分被添加到视图中的过程。git
建立了新模块或组件包含视图,须要注入到主模块和添加路由。这里就不介绍了,主要练习动画。github
在主模块AppModule.ts文件中引入运动的模块BrowserAnimationsModule,web
import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; imports: [ BrowserModule, RouterModule, BrowserAnimationsModule ],
练习使用angular的动画模块,咱们单首创建一个模块练习。api
ng g module my-animations
建立例子1组件app
ng g component my-animations/exp1
在my-animations模块中添加animations.ts文件,并写入动画样式。这个文件里定义的动画即是核心内容。须要有必定的css动画基础才能写出漂亮的动画效果。工具
/**定义动画的ts文件**/ import { trigger, state, style, transition, animate, keyframes } from '@angular/animations'; // 定义一个鼠标点击运动的动画box样式的元素会向左向右移动。 export const boxAnimate = trigger('box', [ // 定义一个状态left state('left', style({ transform: 'translate3d(0,0,0)' })), // 定义另一个状态right state('right', style({ transform: 'translate3d(200%,0,0)' })), // 定义运动过程(从left到right状态) transition('left=>right', animate(2000, keyframes([ style({ transform: 'translate3d(300%,0,0)' }) ]))), // 定义运动过程(从right到left) transition('right=>left', animate(1000, keyframes([ style({ transform: 'translate3d(-100%,0,0)' }), ]))), ]);
在exp1.component.html文件中添加元素动画
<h1>动画实例1</h1> <div style="height: 100px;width: 100px;background-color: black" (click)="start()" [@box]="boxState"></div>
修改exp1.component.ts文件以下this
import { Component, OnInit } from '@angular/core'; import {boxAnimate} from "../animations" @Component({ selector: 'app-exp1', templateUrl: './exp1.component.html', animations: [ boxAnimate ] }) export class Exp1Component implements OnInit { // 定义开始的状态 private boxState: String = 'left'; private _isTrue: Boolean = true; constructor() { } ngOnInit() { } start(): void { console.log('开始运动'); if (this._isTrue) { this.boxState = 'right'; } else { this.boxState = 'left'; } this._isTrue = !this._isTrue; } }
实现一个动画效果大体分为下面几步
动画效果的核心是一个trigger实例,能够参考官方api来使用,不过都是外文,看起来真费劲。不过经过以上例子大体咱们也能明白动画实现的机制。