作者介紹:筆者本身并沒有寫過太多的文章,雖然有自己的個人博客,但是以前也不會去養成寫文章的習慣。之所以寫這篇文章是發現網上寫angular2的animation教程少的可憐,所以自己實踐了一些動畫,并且將這些過程記錄下來,希望自己以后也能回顧一下。
首先,介紹一下angular的animation吧。從angular4開始,animation被獨立出來形成了一個@angular/animations的包。所以記得在使用之前需要安裝一下這個包。
npm install @angular/animations --save (這條命令可以安裝動畫)。
安裝完之后就可以在項目中使用了。
使用animation前,需要在當前組件的Module中導入BrowserAnimationsModule。這樣才能夠在組件中使用動畫。
接下來,講一下編寫動畫的方法,有兩種方式,一種是新建一個ts文件,在ts文件中編寫一個動畫,然后導入到組件中;另一種方式就是直接在組件中編寫。
//新建的一個ts文件 animation.ts
import {trigger,state,translation,style,animate,keyframes} from '@angluar/animations';
export const fadeIn = trigger(
.... //這是第一種方式
)
編寫好動畫之后,將其導入component的animations中。
import {Component} from '@angular/core';
import {fadeIn} from './fadeIn.ts';
@Component({
animations: [fadeIn],
...
})
上面的這種寫法可以將一個動畫復用到多個組件中去,一般寫大型項目時,建議使用這種方式。但是,我接下來的小demo將會使用第二種方式去書寫。
這個小demo就是平時大家都會用到的下拉列表,下圖是我在寫測試的時候寫的:
這兩張圖是,最終狀態的結果圖,下面來看一下中間動畫的源代碼:
import { Component } from '@angular/core';
import {trigger, state, style, animate, keyframes, transition} from '@angular/animations';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [
trigger('animation', [
state('open', style({display: 'block'})),
state('close', style({display: 'none'})),
transition('open => close', animate('330ms', keyframes([
style({height: '*'}), //離場動畫,div塊的高度從自適應逐漸變成0
style({height: '0'})
]))),
transition('close => open', animate('330ms', keyframes([
style({height: '0'}), //進場動畫,div塊的高度從0到自適應的高度
style({height: '*'})
])))
])
]
})
export class AppComponent {
public state = 'close';
public changeOpen() { //點擊展開按鈕時,div塊進場
this.state = 'open';
}
public changeClose() { //點擊離開按鈕時,div塊離場
this.state = 'close';
}
}
整個動畫有兩個狀態‘open’和'close',打開時open,div塊是顯示的,close時,div塊時隱藏的。在整個div塊有一個進場的動畫和離場的動畫。
下面是整個小測試的html和css源碼
<button (click)="changeOpen()">展開</button>
<div class="test-div" [@animation]="state">
<ul>
<li>測試</li>
<li>測試</li>
<li>測試</li>
<li>測試</li>
<li>測試</li>
<li>測試</li>
</ul>
</div>
<button (click)="changeClose()">收起</button>
.test-div{
width: 100px;
position: relative;
overflow: hidden;
}
.test-div ul{
list-style: none;
}
這個小動畫能夠在很多的小場景下使用,如圖:
這是第一次在簡書寫文章,我也只是想寫點有意思的前端小玩意,然后將實現的過程記錄下來,方便以后查看。
注:這篇博文屬于原創博文,如果有問題的可以給我留言,轉載注明出處。