https://github.com/comehope/front-end-daily-challenges
定義 dom,容器包含 2 個元素,branch
代表枝,leaves
代表葉,葉有 6 個子元素,代表 6 個葉片:
<figure class="sapling"> <div class="branch"></div> <div class="leaves"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div> </figure>
居中顯示:
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: black; }
定義容器尺寸,并設置子元素水平居中:
.sapling { position: relative; width: 5em; height: 17.5em; font-size: 10px; display: flex; justify-content: center; }
畫出樹枝:
.branch { position: absolute; width: 0.2em; height: inherit; border-radius: 25%; background: burlywood; }
定義樹葉容器,設置為葉片在垂直方向均勻分布,并且從下到上排列:
.leaves { position: absolute; width: inherit; height: 15em; top: 1em; display: flex; flex-direction: column-reverse; }
設置葉片的尺寸和和背景顏色:
.leaves span { width: 2.5em; height: 2.5em; background-color: limegreen; }
設置左右葉片的各自樣式:
.leaves span:nth-child(odd) { border-bottom-left-radius: 3em; border-top-right-radius: 3em; transform-origin: right bottom; align-self: flex-start; } .leaves span:nth-child(even) { border-bottom-right-radius: 3em; border-top-left-radius: 3em; transform-origin: left bottom; align-self: flex-end; }
至此,靜態(tài)效果繪制完成,接下來開始寫動畫腳本。
引入 GSAP 庫:
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"></script>
聲明一個時間線對象:
let animation = new TimelineMax();
增加樹枝的入場動畫效果,并為這個動畫設置一個標簽 branch
:
animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch');
增加樹葉的入場動畫效果,它的參數(shù)中有 3 個 0.5
,從左到右的含義分別是動畫時長、多個葉片動畫的間隔時長、相對 branch
標簽動畫的延遲時間:
animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch') .staggerFrom('.leaves span', 0.5, {scale: 0, ease: Power1.easeOut}, 0.5, 0.5, 'branch');
增加葉片變黃的動畫效果:
animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch') .staggerFrom('.leaves span', 0.5, {scale: 0, ease: Power1.easeOut}, 0.5, 0.5, 'branch') .to(['.branch', '.leaves span'], 3, {backgroundColor: 'yellow'});
增加淡出效果:
animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch') .staggerFrom('.leaves span', 0.5, {scale: 0, ease: Power1.easeOut}, 0.5, 0.5, 'branch') .to(['.branch', '.leaves span'], 3, {backgroundColor: 'yellow'}) .to(['.branch', '.leaves span'], 1, {autoAlpha: 0});
修改聲明時間線的代碼,使動畫重復播放:
let animation = new TimelineMax({repeat: -1, repeatDelay: 0.5});
大功告成!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com