search
HomeWeb Front-endHTML TutorialCSS秘密花园: 文本动画_html/css_WEB-ITnose

《 CSS Secrets 》是 @Lea Verou 最新著作,这本书讲解了有关于CSS中一些小秘密。是一本CSSer值得一读的一本书,经过一段时间的阅读,我、@南北和@彦子一起将在W3cplus发布一系列相关的读后感,与大家一起分享。

问题

有时候我们想要模拟文本输入的动画效果,就是文本一个一个的出现。这种动画效果特别在科技网站上流行。使用的正确,让你的网站效果直接提到另一个档次上。

通常要实现这样的效果都需要复杂的JavaScript脚本。尽管这只是纯粹的演示,使用CSS实现这样的效果那简直就是白日做梦。怎么可能呢?

欧洲核子研究中心官网 就使用了这种动画效果。

解决方案

实现这个动画思路是包含文本的元素宽度从 0 慢慢过渡(一个字符一个字符)元素内容宽度。你可能意识到这种方法的局限性是什么:它不能在多行文本中运行。值得庆幸的是,大多数时候,只是单行文本上使用这种动画效果,比如说标题。

另外有一点需要注意的是,动画的效果随着时间的增长会有所减弱。动画持续的时间越短动画效果越好,用户体验也越好;持续时间越长,动画效果会让用户感觉很无聊。综上所述,即使技术允许使用在长文本上,但应该尽量避免使用在多行文本上。

让我们开始写代码吧,假设我们将这个效果用在

的标题上,并且给文本设置等宽字体,代码如下:
<h1 id="CSS-is-awesome">CSS is awesome!</h1>

我们可以添加一个简单动画,宽度从 0 过渡到标题内容的宽度:

@keyframes typing {    from { width: 0 }}h1 {    width: 7.7em; /* Width of text */    animation: typing 8s;}

这非常有意义,对吗?然而,正如下图所看到的,这是一个失败的效果,并不是我们需要的东西:

你可能已经猜到问题所在。你会想起使用 white-space:nowrap; 来防止文本换行,因为宽度会增加,行数变为一行。第二,使用 overflow:hidden; 截取溢出文本。解决了这些问题,我们动画才可能像是我们需要的,如下图所示:

  • 显而易见的问题是动画是平滑的,但不是一个一个字符的出现。
  • 不太明显的问题是,到目前为止,使用 em 做为宽度单位,而没有使用 px ,虽然 em 比 px 更好,但效果仍然不佳。而且宽度为 7.7em 是从哪里来的?又是如何计算出来的呢?

解决第一个问题可以通 steps() 处理,就像前面介绍的逐帧动画和闪烁动画一样。不幸的是,我们需要的步骤是字符串的字符数,这对于动态的文本是完全不可能的。然而,稍后我们将看到,使用一小段JavaScript代码可以实现。

解决第二个问题可以使用 ch 单位, ch 单位是 CSS3中新引入的一个单位 , 1ch 的大小和字母 o 的宽度相等。新单位最未知的情况之一是因为大多数情况下,并不太在乎元素宽度是相对于字符 o 宽度。然而,等宽字体是一种特殊的字体。等宽字体每个字符的宽度都和字母 o 宽度一样。因此,在我们示例中宽度就是 15 个字符数的 ch 宽度。

将他们放在一起:

<h1 id="CSS-is-awesome">CSS is awesome!</h1>@keyframes typing {    from {       width: 0;     }}h1 {    width: 15ch; /* Width of text */    overflow: hidden;    white-space: nowrap;    animation: typing 6s steps(15);}

正如你看到的上图。现在我们终于看到了预期的动画效果:我们文本是一个一个字符的出现。然而,它仍然还不完美,难道是哪少了什么吗?

还有最后一个效果,给字符后面添加闪烁的光标。在上一节中,我们知道如何创建闪烁动画。可以通过伪元素来创建闪烁光标,并且使用 opacity 属性,当然伪元素起到的作用也有限,在这个示例中,使用右边框来替代:

@keyframes typing {    from { width: 0 }}@keyframes caret {    50% { border-color: transparent; }}h1 {    width: 15ch; /* Width of text */    overflow: hidden;    white-space: nowrap;    border-right: .05em solid;    animation: typing 6s steps(15),caret 1s steps(1) infinite;}

注意,不同于文本逐个出现的动画,光标符需要不停的闪烁(甚至是所有字符都出来了)。因此给动画设置一个 infinite 关键词,让他无限次播放。同时,我们没有指定边框颜色,主要是让其自动获取文本颜色。如下图所示:

现在我们的动画作品比较完美了,尽管维护不是很容易:根据不同的内容的字符数要为标题设置不同的样式。不过使用JavaScript代码就可以完美的完成这个任务:

$$('h1').forEach(function(h1) {    var len = h1.textContent.length, s = h1.style;    s.width = len + 'ch';    s.animationTimingFunction = "steps("+len+"),steps(1)";});

就只要这几行JS代码,不仅实现了我们要的动画效果,代码也易维护。

注意:也可以使用下面的一段JS代码:

var aH1 = document.getElementsByTagName('h1');for(var i = 0, len = aH1.length; i < len; i++){    var textLen = aH1[i].textContent.length, s = aH1[i].style;    s.width = textLen + 'ch';    s.animationTimingFunction = "steps("+textLen+"),steps(1)";}

这是不错的,浏览器不支持CSS动画会发生什么?从本质上说,他们将忽略所有有关于CSS的 animation 相关的东西,浏览器会能识别:

h1 {    width: 15ch; /* Width of text */    overflow: hidden;    white-space: nowrap;    border-right: .05em solid;}

浏览器不支持动画效果,会降级处理,上面的是支持 ch 效果,下面的是不支持 ch 单位的效果

正如上图所看到的,效果好不好主要取决于浏览器是否支持 ch 单位。如果你想避免底部那个效果,你可以通过 em 做降级处理。如果你不希望光标字符在最后,你可以改变光标字符动画中关键帧中的 border 属性,这样你只会看到一个透明的边框,如下:

@keyframes caret {    50% { border-color: currentColor; }}h1 {    /* ... */    border-right: .05em solid transparent;    animation: typing 6s steps(15),caret 1s steps(1) infinite;}
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment