css加载动画_如何使用纯CSS为您的应用创建漂亮的加载动画

本文将指导你如何仅使用CSS创建一个加载动画,并将其应用于动态应用中。通过创建一个可应用于任何元素的CSS类,实现加载内容时的过渡效果。教程覆盖从基础动画创建到在React应用中模拟数据加载的全过程。
摘要由CSDN通过智能技术生成

css加载动画

If you've been around the internet lately, you've most likely seen a nice subtle loading animation that fills page content before gracefully loading in.

如果您最近上网,您很可能已经看到了一个不错的微妙的加载动画,该动画在正常加载之前先填充页面内容。

Some of the social giants like Facebook even use this approach to give page loading a better experience. How can we do that with just some simple CSS?

一些社交巨头(例如Facebook)甚至使用这种方法来提供更好的页面加载体验。 我们如何只用一些简单CSS来做到这一点?

我们要建造什么? (What are we going to build?)

We're going to create a loading animation using a CSS class that you can apply to pretty much any element you want (within reason).

我们将使用CSS类创建一个加载动画,您可以将其应用于几乎任何想要的元素(在合理的范围内)。

This gives you great flexibility to use it and makes the solution nice and simple with only CSS.

这为您提供了极大的灵活性来使用它,并且仅使用CSS即可使解决方案变得美观而简单。

While the snippet is pretty small and you could just copy and paste it, I'll walk you through what's happening and an example of using it dynamically when loading data.

虽然该代码段很小,您可以复制并粘贴它,但我将向您介绍发生的情况以及在加载数据时动态使用它的示例。

只需要片段吗? (Just want the snippet?)

You can grab it here!

你可以在这里抢!

在学习本教程之前,我是否需要知道如何制作动画? (Do I need to know how to animate before this tutorial?)

No! We'll walk through in detail exactly what you need to do. In fact, the animation in this tutorial is relatively simple, so let's dig in!

没有! 我们将详细详细介绍您需要执行的操作。 实际上,本教程中的动画是相对简单的,因此让我们深入研究吧!

第1部分:创建加载动画 (Part 1: Creating our loading animation)

This first part is going to focus on getting the loading animation together and seeing it on a static HTML website. The goal is to walk through actually creating the snippet. We'll only use HTML and CSS for this part.

第一部分将重点放在将加载动画放在一起并在静态HTML网站上查看它。 目标是逐步创建代码片段。 对于这一部分,我们将仅使用HTML和CSS。

步骤1:创建一些示例内容 (Step 1: Creating some sample content)

To get started, we'll want a little sample content. There's really no restrictions here, you can create this with basic HTML and CSS or you can add this to your Create React App!

首先,我们需要一些示例内容。 此处实际上没有任何限制,您可以使用基本HTML和CSS进行创建,也可以将其添加到您的Create React App中!

For the walk through, I'm going to use HTML and CSS with a few examples of content that will allow us to see this in effect.

在演练中,我将使用HTML和CSS以及一些内容示例,这些示例将使我们看到实际的效果。

To get started, create a new HTML file. Inside that HTML file, fill it with some content that will give us the ability to play with our animation. I'm going to use fillerama which uses lines from my favorite TV show Futurama!

首先,创建一个新HTML文件。 在该HTML文件中,填充一些内容,使我们能够播放动画。 我将使用fillerama ,它使用我最喜欢的电视节目《 Futurama》中的线条!

If you're going to follow along with me, here's what my project looks like:

如果您要跟着我走,这就是我的项目:

my-css-loading-animation-static
- index.html
- main.css

Follow along with the commit!

跟随提交!

步骤2:从基础加载类开始 (Step 2: Starting with a foundation loading class)

For our foundation, let's create a new CSS class. Inside our CSS file, let's add:

作为基础,让我们创建一个新CSS类。 在我们CSS文件中,我们添加:

.loading {
  background: #eceff1;
}

With that class, let's add it to a few or all of our elements. I added it to a few paragraphs, headings, and lists.

通过该类,让我们将其添加到我们的部分或全部元素中。 我将其添加到一些段落,标题和列表中。

<p class="loading">For example...

That gives us a basic background, but we'd probably want to hide that text. When it's loading, we won't have that text yet, so most likely we would want to use filler text or a fixed height. Either way, we can set the color to transparent:

这为我们提供了基本背景,但是我们可能想要隐藏该文本。 加载时,我们还没有该文本,因此最有可能我们要使用填充文本或固定高度。 无论哪种方式,我们都可以将颜色设置为透明:

.loading {
  color: transparent;
  background: #eceff1;
}

If you notice with list elements, whether you apply the class to the top level list element (<ol> or <ul>) vs the list item itself (<li>), it looks like one big block. If we add a little margin to the bottom of all list elements, we can see a different in how they display:

如果您注意到列表元素,则是否将类应用于顶级列表元素( <ol><ul> )还是列表项本身( <li> ),看起来就像一个大块。 如果我们在所有列表元素的底部添加一点空白,我们将看到它们的显示方式有所不同:

li {
  margin-bottom: .5em;
}

And now it's starting to come together, but it kind of just looks like placeholders. So let's animate this to look like it's actually loading.

现在它开始融合在一起,但看起来就像是占位符。 因此,让我们对其进行动画处理,使其看起来好像正在加载。

Follow along with the commit!

跟随提交!

第3步:对加载类进行样式化和动画处理 (Step 3: Styling and animating our loading class)

Before actually animating our class, we need something to animate, so let's add a gradient to our .loading class:

在实际给类动画之前,我们需要制作动画,因此让我们为.loading类添加一个渐变:

.loading {
  color: transparent;
  background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%);
}

This is saying that we want a linear gradient that's tilted at 100 degrees, where we start with #eceff1 and fade to #f6f7f8 at 30% and back to #eceff1 at 70%;

这就是说,我们想要一个倾斜100度的线性渐变 ,从#eceff1开始, #f6f7f8以30%的渐变为#f6f7f8 ,然后回到70%的#eceff1

It's hard to see initially when it's still, it might just look like a glare on your computer! If you'd like to see it before moving on, feel free to play with the colors above to see the gradient.

最初很难看到它静止不动,它看起来就像是计算机上的刺眼光! 如果您想在继续之前先看一下它,请随意使用上面的颜色来查看渐变。

Now that we have something to animate, we'll first need to create a keyframes rule:

现在我们可以制作动画了,我们首先需要创建一个关键帧规则:

@keyframes loading {
  0% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0 50%;
  }
}

This rule when applied will change the background position from starting at 100% of the x-axis to 0% of the x-axis.

应用此规则后,背景位置将从x轴的100%更改为x轴的0%。

With the rule, we can add our animation property to our .loading class:

使用该规则,我们可以将动画属性添加到.loading类中:

.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 to ease-in-out to make it smooth, and tell it to loop forever with infinite.

我们的动画行将关键帧设置为loading ,告诉它持续1.2秒,将计时功能设置为ease-in-out使其平滑,并告诉它infinite循环。

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!

如果您在保存后注意到了这一点,它仍然什么也没做。 这样做的原因是我们将DOM元素的一端设置为另一端的渐变,因此无处可移动!

So let's try also setting a background-size on our .loading class.

因此,让我们尝试还在.loading类上设置background-size

.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!

现在,由于我们的背景超出了DOM元素的范围(您看不到该部分),因此它具有一定的动画空间,并且可以得到动画!

Follow along with the commit!

跟随提交!

第2部分:在动态应用中使用加载动画 (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.

为了向您展示我们如何做到这一点,我们将使用Next.js构建一个简单的React应用程序。

步骤1:使用Next.js创建示例React应用 (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".

它会提示您一些选项,尤其是一个名称,该名称将确定创建项目的目录和项目类型。 我正在使用my-css-loading-animation-dynamic和“默认入门应用程序”。

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:

接下来,让我们替换pages/index.js文件中的内容。 我将从上一个示例中获取内容,但是我们将创建与我们期望它来自API的方式类似的内容。 首先,让我们将内容作为对象添加到return语句上方:

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 <main>, let's replace the content with:

要显示该内容,请在<main>内将其替换为:

<main>
  <h1>{ content.header }</h1>
  <p>{ content.intro }</p>
  <ul>
    { content.list.map((item, i) => {
      return (
        <li key={i}>{ item }</li>
      )
    })}
  </ul>
</main>

And for the styles, you can copy and paste everything from our Part 1 main.css file into the <style> tags at the bottom of our index page. That will leave us with:

对于样式,您可以将第1部分main.css文件中的所有内容复制并粘贴到索引页面底部的<style>标记中。 这将使我们拥有:

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.

这样,我们应该回到在第1部分中完成的类似点,除了我们还没有积极地使用任何加载动画。

Follow along with the commit!

跟随提交!

步骤2:伪造从API加载数据 (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 fashioned setTimeout to preload some "loading" content, and after the setTimeout 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 of useState.

为了伪装我们的加载状态,我们将使用React的useStateuseEffect和一个老式的setTimeout来预加载一些“正在加载”的内容,然后在setTimeout完成后,使用我们的实际数据更新该内容。 同时,我们将知道我们处于一个带有useState单独实例的加载状态。

First, we need to import our dependencies. At the top of our pages/index.js file, add:

首先,我们需要导入依赖项。 在我们的pages/index.js文件的顶部,添加:

import { useState, useEffect } from 'react';

Above our content object, let's add some state:

content对象上方,让我们添加一些状态:

const [loadingState, updateLoadingState] = useState(true);
const [contentState, updateContentState] = useState({})

And in our content, we can update the instances to use that state:

在我们的内容中,我们可以更新实例以使用该状态:

<h1>{ contentState.header }</h1>
<p>{ contentState.intro }</p>
<ul>
  { contentState.list.map((item, i) => {
    return (
      <li key={i}>{ item }</li>
    )
  })}
</ul>

Once you save and load that, you'll first notice we get an error because our list property doesn't exist on our contentState, so we can first fix that:

一旦保存和加载,你会首先注意到,因为我们的,我们得到一个错误list属性不存在于我们的contentState ,所以我们可以先修复程序:

{ Array.isArray(contentState.list) && contentState.list.map((item, i) => {
  return (
    <li key={i}>{ item }</li>
  )
})}

And after that's ready, let's add our setTimeout inside of a useEffect hook to simulate our data loading. Add this under our content object:

准备好之后,让我们在useEffect挂钩中添加setTimeout来模拟数据加载。 将此添加到我们的content对象下:

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.

保存并打开浏览器后,您会发现2秒钟内您没有任何内容,然后将其加载,基本上模拟了异步加载该数据。

Follow along with the commit!

跟随提交!

步骤3:添加加载动画 (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.

现在,我们终于可以添加我们的加载动画了。 因此,为此,我们将使用通过useState设置的加载状态,如果内容正在加载,则将.loading类添加到元素中。

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.

在执行此操作之前,与其将此类单独添加到DOM中的每个项目中,不如使用CSS并将该类添加到父级中,这样做更有意义,因此让我们首先进行操作。

First, update the .loading class to target our elements:

首先,更新.loading类以定位我们的元素:

.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 <main> tag:

然后,我们可以将类动态添加到我们的<main>标签中:

<main className={loadingState ? 'loading' : ''}>

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!

注意:如果使用Sass ,则可以通过在要使用的实例中扩展 .loading类或创建占位符并对其进行扩展来管理加载样式!

And if you refresh the page, you'll notice it's still just a blank page for 2 seconds!

而且,如果刷新页面,您会发现它仍然只是空白页面2秒钟!

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 word Loading for each piece of content:

但是我们可以解决这个问题! 因为我们的.loading类将文本设置为透明,所以我们可以为每个内容简单地添加单词Loading

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.

注意:我们不能在此处使用空白空间,因为仅当在DOM中渲染时,这不能为我们提供高度。

And once you save and reload the page, our first 2 seconds will have a loading state that reflects our content!

保存并重新加载页面后,我们的前2秒钟将处于反映我们内容的加载状态!

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.

此技术可以广泛使用。 作为CSS类,可以轻松轻松地将其添加到每个所需的位置。

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.

如果您不喜欢将Loading文本设置为加载状态,则另一种选择是设置固定高度。 唯一的问题是,它需要更多的维护来调整CSS以匹配加载内容的外观。

Additionally, this won't be perfect. More often than not, you won't know exactly how much copy you have on a page. The goal is to simulate and hint that there will be content and that it's currently loading.

此外,这不是完美的。 通常,您不会确切知道页面上有多少副本。 目标是模拟并暗示将有内容并且当前正在加载。

您最喜欢的加载动画是什么? (What's your favorite loading animation?)

Let me know on Twitter!

Twitter上让我知道!

加入对话! (Join in on the conversation!)

翻译自: https://www.freecodecamp.org/news/how-to-use-css-to-create-a-beautiful-loading-animation-for-your-app/

css加载动画

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值