前端每日實戰:157# 視頻演示如何用純 CSS 創作一個棋盤錯覺動畫(實際上每一行都是平行的)

圖片描述

效果預覽

按下右側的“點擊預覽”按鈕可以在當前頁面預覽,點擊鏈接可以全屏預覽。

https://codepen.io/comehope/pen/VEyoGj

可交互視頻

此視頻是可以交互的,你可以隨時暫停視頻,編輯視頻中的代碼。

請用 chrome, safari, edge 打開觀看。

https://scrimba.com/p/pEgDAM/cppKmsd

源代碼下載

每日前端實戰系列的全部源代碼請從 github 下載:

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

代碼解讀

定義 dom,容器中包含 10 個子元素,每個子元素表示一行:

<div class="container">
    <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;
}

定義容器尺寸,用 vmin 單位,並讓子元素豎向排列:

.container {
    width: 100vmin;
    height: 100vmin;
    display: flex;
    flex-direction: column;
}

設置子元素的背景圖案爲間隔的黑白色塊,頂部有一條細線:

.container span {
    width: inherit;
    height: 10vmin;
    background: 
        linear-gradient(
            gray, gray 0.5vmin,
            transparent 0.5vmin, transparent
        ),
        repeating-linear-gradient(
            to right,
            black, black 10vmin,
            transparent 10vmin, transparent 20vmin
        )
}

在容器底部補一條細線:

.container {
    border-bottom: 0.5vmin solid gray;
}

增加動畫效果,讓奇數行的背景向右移動半個色塊的位置,移動之後看起來好像奇數行右寬左窄,偶數行左寬右窄,這是一種錯覺:

.container span:nth-child(odd) {
    animation: move 5s linear infinite;
}

@keyframes move {
    0%, 55%, 100% {
        background-position: 0 0;
    }

    5%, 50% {
        background-position: 5vmin 0;
    }
}

讓偶數行的背景也移動起來,產生相反方向的錯覺:

.container span:nth-child(even) {
    animation: move 5s linear infinite reverse;
}

大功告成!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章