目錄
Starting with the text
The cursor
JavaScript animation
Animating multiple words
Bonus
首頁 web前端 css教學 打字機動畫處理您投入的任何內容

打字機動畫處理您投入的任何內容

Mar 22, 2025 am 09:55 AM

Typewriter Animation That Handles Anything You Throw at It

I watched Kevin Powell’s video where he was able to recreate a nice typewriter-like animation using CSS. It’s neat and you should definitely check it out because there are bonafide CSS tricks in there. I’m sure you’ve seen other CSS attempts at this, including this site’s very own snippet.

Like Kevin, I decided to recreate the animation, but open it up to JavaScript. That way, we have a few extra tools that can make the typing feel a little more natural and even more dynamic. Many of the CSS solutions rely on magic numbers based on the length of the text, but with JavaScript, we can make something that’s capable of taking any text we throw at it.

So, let’s do that. In this tutorial, I’m going to show that we can animate multiple words just by changing the actual text. No need to modify the code every time you add a new word because JavaScript will do that for you!

Starting with the text

Let’s start with text. We are using a monospace font to achieve the effect. Why? Because each character or letter occupies an equal amount of horizontal space in a monospaced font, which will come handy when we’ll use the concept of steps() while animating the text. Things are much more predictable when we already know the exact width of a character and all characters share the same width.

We have three elements placed inside a container: one element for the actual text, one for hiding the text, and one for animating the cursor.

<div >
  <div ></div>
  <div >Typing Animation</div>
  <div ></div>
</div>
登入後複製

We could use ::before and ::after pseudo-elements here, but they aren’t great for JavaScript. Pseudo-elements are not part of the DOM, but instead are used as extra hooks for styling an element in CSS. It’d be better to work with real elements.

We’re completely hiding the text behind the .text_hide element. That’s key. It’s an empty div that stretches the width of the text and blocks it out until the animation starts—that’s when we start to see the text move out from behind the element.

In order to cover the entire text element, position the .text_hide element on top of the text element having the same height and width as that of the text element. Remember to set the background-color of the .text_hide element exactly same as that of the background surrounding the text so everything blends in together.

.container {
  position: relative;
}
.text {
  font-family: 'Roboto Mono', monospace;
  font-size: 2rem;
}
.text_hide {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
}
登入後複製

The cursor

Next, let’s make that little cursor thing that blinks as the text is being typed. We’ll hold off on the blinking part for just a moment and focus just on the cursor itself.

Let’s make another element with class .text_cursor. The properties are going to be similar to the .text_hide element with a minor difference: instead of setting a background-color, we will keep the background-color transparent (since its technically unnecessary, then add a border to the left edge of the new .text_cursor element.

.text_cursor{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: transparent;
  border-left: 3px solid black;
}
登入後複製

Now we get something that looks like a cursor that’s ready to move as the text moves:

JavaScript animation

Now comes the super fun part—let’s animate this stuff with JavaScript! We’ll start by wrapping everything inside a function called typing_animation().

function typing_animation(){
  // code here
}
typing_animation();
登入後複製

Next task is to store each and every character of text in a single array using the split() method. This divides the string into a substring that has only one character and an array containing all the substrings is returned.

function typing_animation(){
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
}
登入後複製

For example, if we take “Typing Animation” as a string, then the output is:

We can also determine the total number of characters in the string. In order to get just the words in the string, we replace split("") with split(" "). Note that there is a difference between the two. Here, " " acts as a separator. Whenever we encounter a single space, it will terminate the substring and store it as an array element. Then the process goes on for the entire string.

function typing_animation(){
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
  let all_words = text_element.innerHTML.split(" ");
}
登入後複製

For example, for a string ‘Typing Animation’, the output will be,

Now, let’s calculate the length of the entire string as well as the length of each and every individual word.

function typing_animation() {
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
  let all_words = text_element.innerHTML.split(" ");
  let text_len = text_array.length;

  const word_len = all_words.map((word) => {
    return word.length;
  });
}
登入後複製

To get the length of the entire string, we have to access the length of the array containing all the characters as individual elements. If we’re talking about the length of a single word, then we can use the map() method, which accesses one word at a time from the all_words array and then stores the length of the word into a new array called word_len. Both the arrays have the same number of elements, but one contains the actual word as an element, and the other has the length of the word as an element.

Now we can animate! We’re using the Web Animation API because we’re going with pure JavaScript here—no CSS animations for us in this example.

First, let’s animate the cursor. It needs to blink on and off infinitely. We need keyframes and animation properties, both of which will be stored in their own JavaScript object. Here are the keyframes:

document.querySelector(".text_cursor").animate([
  {
    opacity: 0
  },
  {
    opacity: 0, offset: 0.7
  },
  {
    opacity: 1
  }
], cursor_timings);
登入後複製

We have defined three keyframes as objects which are stored in an array. The term offset: 0.7 simply means that after 70% completion of the animation, the opacity will transition from 0 to 1.

Now, we have to define the animation properties. For that, let’s create a JavaScript object that holds them together:

let cursor_timings = {
  duration: 700, // milliseconds (0.7 seconds)
  iterations: Infinity, // number of times the animation will work
  easing: 'cubic-bezier(0,.26,.44,.93)' // timing-function
}
登入後複製

We can give the animation a name, just like this:

let animation = document.querySelector(".text_cursor").animate([
  // keyframes
], //properties);
登入後複製

Here’s a demo of what we have done so far:

Great! Now, let’s animate the .text_hide element that, true to its name, hides the text. We define animation properties for this element:

let timings = {
  easing: `steps(${Number(word_len[0])}, end)`,
  delay: 2000, // milliseconds
  duration: 2000, // milliseconds
  fill: 'forwards'
}
登入後複製

The easing property defines how the rate of animation will change over time. Here, we have used the steps() timing function. This animates the element in discrete segments rather than a smooth continuous animation—you know, for a more natural typing movement. For example, the duration of the animation is two seconds, so the steps() function animates the element in 9 steps (one step for each character in “Animation”) for two seconds, where each step has a duration of 2/9 = 0.22 seconds.

The end argument makes the element stay in its initial state until the duration of first step is complete. This argument is optional and its default value is set to end. If you want an in-depth insight on steps(), then you can refer this awesome article by Joni Trythall.

The fill property is the same as animation-fill-mode property in CSS. By setting its value to forwards, the element will stay at the same position as defined by the last keyframe after the animation gets completed.

Next, we will define the keyframes.

let reveal_animation_1 = document.querySelector(".text_hide").animate([
  { left: '0%' },
  { left: `${(100 / text_len) * (word_len[0])}%` }
], timings);
登入後複製

Right now we are animating just one word. Later, we will see how to animate multiple words.

The last keyframe is crucial. Let’s say we want to animate the word “Animation.” Its length is 9 (as there are nine characters) and we know that it’s getting stored as a variable thanks to our typing_animation() function. The declaration 100/text_len results to 100/9, or 11.11%, which is the width of each and every character in the word “Animation.” That means the width of each and every character is 11.11% the width of the entire word. If we multiply this value by the length of the first word (which in our case is 9), then we get 100%. Yes, we could have directly written 100% instead of doing all this stuff. But this logic will help us when we are animating multiple words.

The result of all of this is that the .text_hide element animates from left: 0% to left: 100%. In other words, the width of this element decreases from 100% to 0% as it moves along.

We have to add the same animation to the .text_cursor element as well because we want it to transition from left to right along with the .text_hide element.

Yayy! We animated a single word. What if we want to animate multiple words? Let’s do that next.

Animating multiple words

Let’s say we have two words we want typed out, perhaps “Typing Animation.” We animate the first word by following the same procedure we did last time. This time, however, we are changing the easing function value in the animation properties.

let timings = {
  easing: `steps(${Number(word_len[0] + 1)}, end)`,
  delay: 2000,
  duration: 2000,
  fill: 'forwards'
}
登入後複製

We have increased the number by one step. Why? Well, what about a single space after a word? We must take that into consideration. But, what if there is only one word in a sentence? For that, we will write an if condition where, if the number of words is equal to 1, then steps(${Number(word_len[0])}, end). If the number of words is not equal to 1, then steps(${Number(word_len[0] + 1)}, end).

function typing_animation() {
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
  let all_words = text_element.innerHTML.split(" ");
  let text_len = text_array.length;
  const word_len = all_words.map((word) => {
    return word.length;
  })
  let timings = {
    easing: `steps(${Number(word_len[0])}, end)`,
    delay: 2000,
    duration: 2000,
    fill: 'forwards'
  }
  let cursor_timings = {
    duration: 700,
    iterations: Infinity,
    easing: 'cubic-bezier(0,.26,.44,.93)'
  }
  document.querySelector(".text_cursor").animate([
    {
      opacity: 0
    },
    {
      opacity: 0, offset: 0.7
    },
    {
      opacity: 1
    }
  ], cursor_timings);
  if (all_words.length == 1) {
    timings.easing = `steps(${Number(word_len[0])}, end)`;
    let reveal_animation_1 = document.querySelector(".text_hide").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0])}%` }
    ], timings);
    document.querySelector(".text_cursor").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0])}%` }
    ], timings);
  } else {
    document.querySelector(".text_hide").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0] + 1)}%` }
    ], timings);
    document.querySelector(".text_cursor").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0] + 1)}%` }
  ], timings);
  }
}
typing_animation();
登入後複製

For more than one word, we use a for loop to iterate and animate every word that follows the first word.

for(let i = 1; i < all_words.length; i++){
  // code
}
登入後複製

Why did we take i = 1? Because by the time this for loop is executed, the first word has already been animated.

Next, we will access the length of the respective word:

for(let i = 1; i < all_words.length; i++){
  const single_word_len = word_len[i];
}
登入後複製

Let’s also define the animation properties for all words that come after the first one.

// the following code goes inside the for loop
let timings_2 = {
  easing: `steps(${Number(single_word_len + 1)}, end)`,
  delay: (2 * (i + 1) + (2 * i)) * (1000),
  duration: 2000,
  fill: 'forwards'
}
登入後複製

The most important thing here is the delay property. As you know, for the first word, we simply had the delay property set to two seconds; but now we have to increase the delay for the words following the first word in a dynamic way.

The first word has a delay of two seconds. The duration of its animation is also two seconds which, together, makes four total seconds. But there should be some interval between animating the first and the second word to make the animation more realistic. What we can do is add a two-second delay between each word instead of one. That makes the second word’s overall delay 2 + 2 + 2, or six seconds. Similarly, the total delay to animate the third word is 10 seconds, and so on.

The function for this pattern goes something like this:

(2 * (i + 1) + (2 * i)) * (1000)
登入後複製

…where we’re multiplying by 1000 to convert seconds to milliseconds.

The longer the word, the faster it is revealed. Why? Because the duration remains the same no matter how lengthy the word is. Play around with the duration and delay properties to get things just right.

Remember when we changed the steps() value by taking into consideration a single space after a word? In the same way, the last word in the sentence doesn’t have a space after it, and thus, we should take that into consideration in another if statement.

// the following code goes inside the for loop
if (i == (all_words.length - 1)) {
  timings_2.easing = `steps(${Number(single_word_len)}, end)`;
  let reveal_animation_2 = document.querySelector(".text_hide").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i]))}%` }
  ], timings_2);
  document.querySelector(".text_cursor").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i]))}%` }
  ], timings_2);
} else {
  document.querySelector(".text_hide").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i] + 1))}%` }
  ], timings_2);
  document.querySelector(".text_cursor").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i] + 1))}%` }
  ], timings_2);
}
登入後複製

What’s that left_instance variable? We haven’t discussed it, yet it is the most crucial part of what we’re doing. Let me explain it.

0% is the initial value of the first word’s left property. But, the second word’s initial value should equal the first word’s final left property value.

if (i == 1) {
  var left_instance = (100 / text_len) * (word_len[i - 1] + 1);
}
登入後複製

word_len[i - 1] + 1 refers to the length of the previous word (including a white space).

We have two words, “Typing Animation.” That makes text_len equal 16 meaning that each character is 6.25% of the full width (100/text_len = 100/16) which is multiplied by the length of the first word, 7. All that math gives us 43.75 which is, in fact, the width of the first word. In other words, the width of the first word is 43.75% the width of the entire string. This means that the second word starts animating from where the first word left off.

Last, let’s update the left_instance variable at the end of the for loop:

left_instance = left_instance + ((100 / text_len) * (word_len[i] + 1));
登入後複製

You can now enter as many words as you want in HTML and the animation just works!

Bonus

Have you noticed that the animation only runs once? What if we want to loop it infinitely? It’s possible:

There we go: a more robust JavaScript version of a typewriting animation. It’s super cool that CSS also has an approach (or even multiple approaches) to do the same sort of thing. CSS might even be the better approach in a given situation. But when we need enhancements that push beyond what CSS can handle, sprinkling in some JavaScript does the trick quite nicely. In this case, we added support for all words, regardless of how many characters they contain, and the ability to animate multiple words. And, with a small extra delay between words, we get a super natural-looking animation.

That’s it, hope you found this interesting! Signing off.

以上是打字機動畫處理您投入的任何內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1658
14
CakePHP 教程
1415
52
Laravel 教程
1309
25
PHP教程
1257
29
C# 教程
1231
24
Google字體可變字體 Google字體可變字體 Apr 09, 2025 am 10:42 AM

我看到Google字體推出了新設計(Tweet)。與上一次大型重新設計相比,這感覺更加迭代。我幾乎無法分辨出區別

如何使用HTML,CSS和JavaScript創建動畫倒計時計時器 如何使用HTML,CSS和JavaScript創建動畫倒計時計時器 Apr 11, 2025 am 11:29 AM

您是否曾經在項目上需要一個倒計時計時器?對於這樣的東西,可以自然訪問插件,但實際上更多

HTML數據屬性指南 HTML數據屬性指南 Apr 11, 2025 am 11:50 AM

您想了解的有關HTML,CSS和JavaScript中數據屬性的所有信息。

使Sass更快的概念證明 使Sass更快的概念證明 Apr 16, 2025 am 10:38 AM

在一個新項目開始時,Sass彙編發生在眼睛的眨眼中。感覺很棒,尤其是當它與browsersync配對時,它重新加載

我們如何創建一個在SVG中生成格子呢模式的靜態站點 我們如何創建一個在SVG中生成格子呢模式的靜態站點 Apr 09, 2025 am 11:29 AM

格子呢是一塊圖案布,通常與蘇格蘭有關,尤其是他們時尚的蘇格蘭語。在Tar​​tanify.com上,我們收集了5,000多個格子呢

如何在WordPress主題中構建VUE組件 如何在WordPress主題中構建VUE組件 Apr 11, 2025 am 11:03 AM

內聯式模板指令使我們能夠將豐富的VUE組件構建為對現有WordPress標記的逐步增強。

php是A-OK用於模板 php是A-OK用於模板 Apr 11, 2025 am 11:04 AM

PHP模板通常會因促進Subpar代碼而變得不良說唱,但這並不是這樣的情況。讓我們看一下PHP項目如何執行基本的

編程SASS創建可訪問的顏色組合 編程SASS創建可訪問的顏色組合 Apr 09, 2025 am 11:30 AM

我們一直在尋求使網絡更容易訪問。顏色對比只是數學,因此Sass可以幫助涵蓋設計師可能錯過的邊緣案例。

See all articles