前端每日實戰:8# 視頻演示如何用純 CSS 創做一個充電 loader 特效

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕在當前頁面預覽,點擊連接全屏預覽。css

https://codepen.io/zhang-ou/pen/deNqdVhtml

可交互視頻教程

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。git

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

https://scrimba.com/c/cvrwJAKchrome

源代碼下載

請從 github 下載。dom

https://github.com/comehope/front-end-daily-challenges/tree/master/008-charging-loader-animation函數

代碼解讀

定義 dom,只有一個容器元素:flex

<div class="battery"></div>

居中顯示:動畫

html, body {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(to bottom, teal, aqua);
}

畫出電池的主體輪廓:spa

.battery {
    width: 6em;
    height: 3em;
    color: midnightblue;
    border: 0.5em solid currentColor;
    border-radius: 0.2em;
    font-size: 2em;
}

畫出電池的突起:

.battery {
    position: relative;
}

.battery::after {
    content: '';
    position: absolute;
    width: 0.5em;
    height: 2em;
    background-color: currentColor;
    top: 0.5em;
    right: -1em;
    border-radius: 0 0.2em 0.2em 0;
}

畫出充電電量:

.battery {
    background-image: linear-gradient(to right, whitesmoke, whitesmoke);
    background-repeat: no-repeat;
    background-size: 30% 80%;
    background-position: 0.3em 50%;
}

定義和應用動畫效果:

@keyframes charge {
    from {
        background-size: 10% 80%;
    }

    to {
        background-size: 95% 80%;
    }
}

.battery {
    animation: charge 5s linear infinite;
}

最後,把動畫的時間函數由線性變化改成步長變化:

.battery {
    animation: charge 5s steps(8) infinite;
}

大功告成!

知識點

linear-gradient() https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

background-size https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

background-position https://developer.mozilla.org/en-US/docs/Web/CSS/background-position

steps() https://developer.mozilla.org/en-US/docs/Web/CSS/single-transition-timing-function#Timing_functions

currentColor https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Values

border-radius https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius

相關文章
相關標籤/搜索