Ha nemrégiben járt az interneten, akkor valószínűleg látott egy szép finom betöltő animációt, amely kitölti az oldal tartalmát, mielőtt kecsesen betöltené.
Néhány közösségi óriás, mint a Facebook, még ezt a megközelítést is használja, hogy jobb élményt nyújtson az oldalbetöltésnek. Hogyan tehetjük meg ezt csak néhány egyszerű CSS-sel?
- Mit fogunk építeni?
- Csak a részletet akarja?
- 1. rész: Betöltő animációnk létrehozása
- 2. rész: Betöltő animációnk használata dinamikus alkalmazásban
Mit fogunk építeni?
Létrehozunk egy betöltő animációt egy CSS osztály felhasználásával, amelyet nagyjából bármely elemre alkalmazhatsz (ésszerű határokon belül).

Ez nagy rugalmasságot biztosít a használatához, és a megoldást csak CSS-sel teszi szépé és egyszerűvé.
Bár a kódrészlet elég kicsi, és egyszerűen másolhatja és beillesztheti, végigvezetek benneteket a történéseken, és példát adok dinamikus használatára az adatok betöltésekor.
Csak a részletet akarja?
Itt megragadhatja!
CSS Animáció betöltése CSS Animáció betöltése. GitHub Gist: azonnal megoszthatja a kódot, a jegyzeteket és a kivonatokat.

Tudnom kell, hogyan kell animálni a bemutató előtt?
Nem! Részletesen áttekintjük, mit kell tennie. Valójában az oktatóanyag animációja viszonylag egyszerű, ezért ássunk bele!
1. rész: Betöltő animációnk létrehozása
Ez az első rész a betöltő animáció összegyűjtésére és statikus HTML webhelyen való megtekintésére összpontosít. A cél a részlet létrehozása. Csak HTML-t és CSS-t fogunk használni ehhez a részhez.
1. lépés: Néhány tartalom létrehozása
A kezdéshez szükségünk lesz egy kis mintatartalomra. Itt valóban nincsenek korlátozások, ezt létrehozhatja alapvető HTML és CSS használatával, vagy hozzáadhatja a Create React alkalmazáshoz!
Az áttekintéshez a HTML-t és a CSS-t fogom használni, néhány tartalmi példával, amelyek lehetővé teszik számunkra, hogy ezt ténylegesen lássuk.
A kezdéshez hozzon létre egy új HTML fájlt. A HTML fájl belsejében töltsön be olyan tartalommal, amely lehetővé teszi számunkra, hogy az animációnkkal játszhassunk. A filleramát fogom használni, amely a kedvenc Futurama tévéműsorom sorait használja!

Ha velem akarsz követni, a projektem így néz ki:
my-css-loading-animation-static - index.html - main.css
Kövesse az elkötelezettséggel együtt!
2. lépés: Kezdve egy alapozó rakodási osztállyal
Alapítványunk számára hozzunk létre egy új CSS osztályt. A CSS fájlunkon belül tegyük hozzá:
.loading { background: #eceff1; }
Ezzel az osztállyal adjuk hozzá néhány vagy az összes elemünkhöz. Hozzáadtam néhány bekezdéshez, címsorhoz és listához.
For example...

Ez ad egy alapvető hátteret, de valószínűleg el szeretnénk rejteni ezt a szöveget. Betöltéskor még nem lesz meg a szöveg, ezért valószínűleg kitöltő szöveget vagy fix magasságot szeretnénk használni. Akárhogy is, átlátszóvá állíthatjuk a színt:
.loading { color: transparent; background: #eceff1; }

Ha listaelemekkel veszi észre, alkalmazza-e az osztályt a legfelső szintű listaelemre (
-
vagy
), úgy néz ki, mint egy nagy blokk. Ha egy kis margót adunk az összes listaelem aljára, akkor láthatunk egy mást a megjelenítésükben:
li { margin-bottom: .5em; }
És most kezd összeállni, de ez csak úgy néz ki, mint a helyőrzők. Tehát animáljuk ezt úgy, hogy valóban betöltődjön.
Kövesse az elkötelezettséggel együtt!
3. lépés: Stílus és animáció a betöltési osztályról
Mielőtt valóban animálnánk az osztályunkat, szükségünk van valamire az animációra, ezért adjunk hozzá egy színátmenetet az
.loading
osztályunkhoz:.loading { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); }
Ez azt jelenti, hogy egy lineáris gradienst akarunk, amely 100 fokon dől meg, ahol 30% -kal indulunk
#eceff1
és elhalványulunk#f6f7f8
,#eceff1
majd 70% -ra haladunk ;Kezdetben nehéz látni, amikor még mozdulatlan, lehet, hogy csak egy tükröződésnek tűnik a számítógépén! Ha szeretné megnézni, mielőtt továbblép, nyugodtan játszhat a fenti színekkel, hogy lássa a színátmenetet.
Most, hogy van mit animálnunk, először létre kell hoznunk egy kulcskép-szabályt:
@keyframes loading { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }
Ez a szabály alkalmazásakor megváltoztatja a háttér helyzetét az x-tengely 100% -áról az x-tengely 0% -ára.
A szabály alapján felvehetjük animációs tulajdonságunkat az
.loading
osztályunkba:.loading { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); animation: loading 1.2s ease-in-out infinite; }
Our animation line is setting the keyframe to
loading
, telling it to last for 1.2 seconds, setting the timing function toease-in-out
to make it smooth, and tell it to loop forever withinfinite
.If you notice though after saving that, it's still not doing anything. The reason for this is we're setting our gradient from one end of the DOM element to the other, so there's nowhere to move!
So let's try also setting a
background-size
on our.loading
class..loading { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); background-size: 400%; animation: loading 1.2s ease-in-out infinite; }
Now, since our background expands beyond our DOM element (you can't see that part), it has some space to animate with and we get our animation!
Follow along with the commit!
Part 2: Using our loading animation in a dynamic app
Now that we have our loading animation, let's put it into action with a basic example where we fake a loading state.
The trick with actually using this is typically we don't have the actual content available, so in most cases, we have to fake it.
To show you how we can do this, we're going to build a simple React app with Next.js.
Step 1: Creating an example React app with Next.js
Navigate to the directory you want to create your new project in and run:
yarn create next-app # or npm init next-app
It will prompt you with some options, particularly a name which will determine the directory the project is created in and the type of project. I'm using
my-css-loading-animation-dynamic
and the "Default Starter App".Once installed, navigate into your new directory and start up your development server:
cd [directory] yarn dev # or npm run dev
Next, let's replace the content in our
pages/index.js
file. I'm going to derive the content from the previous example, but we'll create it similar to how we might expect it to come from an API. First, let's add our content as an object above our return statement:const content = { header: `So, how 'bout them Knicks?`, intro: `What are their names? I'm Santa Claus! This opera's as lousy as it is brilliant! Your lyrics lack subtlety. You can't just have your characters announce how they feel. That makes me feel angry! Good news, everyone! I've taught the toaster to feel love!`, list: [ `Yes! In your face, Gandhi!`, `So I really am important? How I feel when I'm drunk is correct?`, `Who are those horrible orange men?` ] }
To display that content, inside
, let's replace the content with:
{ content.header }
{ content.intro }
-
{ content.list.map((item, i) => { return (
- { item } ) })}
And for the styles, you can copy and paste everything from our Part 1
main.css
file into thetags at the bottom of our index page. That will leave us with:
With that, we should be back to a similar point we finished at in Part 1 except we're not actively using any of the loading animations yet.
Follow along with the commit!
Step 2: Faking loading data from an API
The example we're working with is pretty simple. You'd probably see this coming pre-generated statically, but this helps us create a realistic demo that we can test our loading animation with.
To fake our loading state, we're going to use React's
useState
,useEffect
, and an old fashionedsetTimeout
to preload some "loading" content, and after thesetTimeout
finishes, update that content with our actual data. In the meantime, we'll know that we're in a loading state with a separate instance ofuseState
.First, we need to import our dependencies. At the top of our
pages/index.js
file, add:import { useState, useEffect } from 'react';
Above our
content
object, let's add some state:const [loadingState, updateLoadingState] = useState(true); const [contentState, updateContentState] = useState({})
And in our content, we can update the instances to use that state:
{ contentState.header }
{ contentState.intro }
-
{ contentState.list.map((item, i) => { return (
- { item } ) })}
Once you save and load that, you'll first notice we get an error because our
list
property doesn't exist on ourcontentState
, so we can first fix that:{ Array.isArray(contentState.list) && contentState.list.map((item, i) => { return (
- { item }
) })}And after that's ready, let's add our
setTimeout
inside of auseEffect
hook to simulate our data loading. Add this under ourcontent
object:useEffect(() => { setTimeout(() => { updateContentState(content); updateLoadingState(false) }, 2000); }, [])
Once you save and open up your browser, you'll notice that for 2 seconds you don't have any content and then it loads in, basically simulating loading that data asynchronously.
Follow along with the commit!
Step 3: Adding our loading animation
Now we can finally add our loading animation. So to do this, we're going to use our loading state we set up using
useState
and if the content is loading, add our.loading
class to our elements.Before we do that, instead of individually adding this class to each item in the DOM, it might make more sense to do so using CSS and adding the class to the parent, so let's do that first.
First, update the
.loading
class to target our elements:.loading h1, .loading p, .loading li { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); background-size: 400%; animation: loading 1.2s ease-in-out infinite; }
Then we can dynamically add our class to our
tag:
Note: if you use Sass, you can manage your loading styles by extending the
.loading
class in the instances you want to use it or create a placeholder and extend that!And if you refresh the page, you'll notice it's still just a blank page for 2 seconds!
The issue, is when we load our content, nothing exists inside of our tags that can that would allow the line-height of the elements to give it a height.
But we can fix that! Because our
.loading
class sets our text to transparent, we can simply add the wordLoading
for each piece of content:const [contentState, updateContentState] = useState({ header: 'Loading', intro: 'Loading', list: [ 'Loading', 'Loading', 'Loading' ] })
Note: We can't use an empty space here because that alone won't provide us with a height when rendered in the DOM.
And once you save and reload the page, our first 2 seconds will have a loading state that reflects our content!
Follow along with the commit!
Some additional thoughts
This technique can be used pretty broadly. Being a CSS class makes it nice and easy to add where every you want.
If you're not a fan of setting the
Loading
text for the loading state, another option is to set a fixed height. The only issue with that is it requires more maintenance for tweaking the CSS to match what the content loading in will look like.Ezenkívül ez nem lesz tökéletes. Gyakrabban nem fogja tudni, hogy mennyi példánya van egy oldalon. A cél annak szimulálása és utalása, hogy lesz tartalom, és hogy éppen töltődik be.
Mi a kedvenc animációs animációd?
Mondd meg a Twitteren!
Csatlakozzon a beszélgetéshez!
Ha egy oldal betöltésére vársz, segít megtudni, hogy valami működik a háttérben.
Tehát létre kell hoznia egy szép betöltő animációt az alkalmazásához.
Ezért írta @colbyfayock ezt az útmutatót, amely bemutatja, hogyan lehet tiszta CSS-sel felépíteni az animációt .//t.co/h8hGwqZ3sl
- freeCodeCamp.org (@freeCodeCamp) 2020. május 24- ? Kövess a Twitteren
- ? ️ Iratkozzon fel a Youtube-ra
- ✉️ Iratkozzon fel a hírlevelemre
) vs maga a listaelem (