如何使用純CSS 實作類別似於旗幟飄揚動畫效果(附源碼)

來源:互聯網
上載者:User
本篇文章給大家帶來的內容是關於如何使用純CSS 實作類別似於旗幟飄揚動畫效果(附源碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

效果預覽

原始碼下載

https://github.com/comehope/front-end-daily-challenges

代碼解讀

定義 dom,容器中包含 15 個元素:

<div class="flag">    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span>    <span></span></div>

置中顯示:

body {    margin: 0;    height: 100vh;    display: flex;    align-items: center;    justify-content: center;    background-color: black;}

定義容器尺寸:

.flag {    width: 10em;    height: 15em;    font-size: 20px;}

設定線條樣式:

.flag span {    width: 0.25em;    height: inherit;    background-color: deepskyblue;}

讓線條平鋪:

.flag {    display: flex;    justify-content: space-between;}

增加 3d 透視效果:

.flag {    transform: perspective(500px) rotateY(-20deg);}

定義左右移動的動畫效果:

.flag span {    animation: wave 1.5s ease-in-out infinite alternate;}@keyframes wave {    to {        transform: translateX(2em);    }}

設定元素變數值:

.flag span:nth-child(1) {    --n: 1;}.flag span:nth-child(2) {    --n: 2;}/* 共 15 個元素,每元素的 --n 變數值等於它的序號。 *//* 中間代碼略 …… */.flag span:nth-child(14) {    --n: 14;}.flag span:nth-child(15) {    --n: 15;}

讓各線條分別延時啟動動畫,形成旗幟飄揚的效果:

.flag span {    animation-delay: calc(var(--n) * -0.1s);}

最後,增加光影效果:

.flag span {    background-color: ghostwhite;}@keyframes wave {    to {        transform: translateX(2em);        background-color: deepskyblue;    }}

大功告成!

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.