返回目錄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來使用,不過都是外文,看起來真費勁。不過經過以上例子大體咱們也能明白動畫實現的機制。