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