簡単に言うと
cssのアニメーション(アニメーションプロパティ)を利用することで、テキスト表示のタイプライター効果を実現します。
単一行
一連の考え
実装手順:
- テキスト ボックスのプロパティを等幅フォントに設定し、テキスト ボックス内の単語数を計算し、テキスト サイズ、相対的なレイアウトなどを設定します。
- テキスト ボックスを非表示にし、アニメーションを通じてテキスト ボックスの幅を変更し、アニメーション スピード カーブの組み込み CSS 関数 Steps() を使用してステップ アニメーションにし、アニメーション モードを順方向に設定してスタイルを保持します。アニメーションの最後のフレーム。
- 疑似要素を使用して境界プロパティと絶対レイアウトを設定し、カーソルをシミュレートし、アニメーションを使用してかすかな効果を実現します。
コード
ここでは、幅の変更とステップ アニメーションを組み合わせて効果を実現しています。幅の単位は em で、値はこの行のテキストの量に応じて計算されます。
<template>
<div class="container">
<div class="text__box one">这是一个打字机效果1!!!</div>
<!-- <div class="text__box two">这是一个打字机效果2!!!</div>
<div class="text__box three">这是一个打字机效果3!!!</div>
<div class="text__box four">这是一个打字机效果4!!!</div> -->
</div>
</template>
<script lang="ts" setup>
import {
reactive, ref, toRefs, onBeforeMount, onMounted, computed } from "vue";
</script>
<style lang="scss" scoped>
.container {
position: relative;
margin-top: 100px;
margin-left: 100px;
}
.text__box {
position: relative;
overflow: hidden;
width: 0;
font-size: 32px;
line-height: 34px;
font-family: "Courier New", Courier, monospace;
white-space: nowrap;
animation: width 2s steps(13) forwards;
&::after {
content: "";
position: absolute;
right: 0px;
height: 32px;
border-right: 1px solid #000;
animation: showInfinite 0.5s infinite both;
}
}
.one {
animation-delay: 0s;
}
@keyframes width {
0% {
width: 0;
}
100% {
width: 13em; // 单位em,表示一个字体的宽度
}
}
@keyframes showInfinite {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
</style>
効果
複数行
一連の考え
複数行タイプライターの実現アイデアは、単一行に基づいて実行されます。
アニメーション遅延プロパティを使用して、単一行の実装から複数行の実装に移行する効果を実現します。
なお、カーソルの処理は無限にアニメーションさせることができるカーソルの最後の行であり、それ以外の行はカーソルアニメーションの実行回数を指定することができる。
コード
<template>
<div class="container">
<div class="text__box one">这是一个打字机效果1!!!</div>
<div class="text__box two">这是一个打字机效果2!!!</div>
<div class="text__box three">这是一个打字机效果3!!!</div>
<div class="text__box four">这是一个打字机效果4!!!</div>
</div>
</template>
<script lang="ts" setup>
import {
reactive, ref, toRefs, onBeforeMount, onMounted, computed } from "vue";
</script>
<style lang="scss" scoped>
.container {
position: relative;
margin-top: 100px;
margin-left: 100px;
}
.text__box {
position: relative;
overflow: hidden;
width: 0;
font-size: 32px;
line-height: 34px;
font-family: "Courier New", Courier, monospace;
white-space: nowrap;
animation: width 2s steps(13) forwards;
&::after {
content: "";
position: absolute;
right: 0px;
height: 32px;
border-right: 1px solid #000;
animation: showInfinite 0.5s 5 both; // 执行5次
}
}
.one {
animation-delay: 0s;
}
.two {
animation-delay: 2s;
&::after {
animation-delay: 2s;
}
}
.three {
animation-delay: 4s;
&::after {
animation-delay: 4s;
}
}
.four {
animation-delay: 6s;
&::after {
animation-delay: 6s;
animation: showInfinite 0.5s infinite both;
}
}
@keyframes width {
0% {
width: 0;
}
100% {
width: 13em; // 单位em,表示一个字体的宽度
}
}
@keyframes showInfinite {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
</style>
効果
エピローグ
ここでの主な用途は歩幅アニメーションですが、テキストの 1 行の長さに注目し、その長さに応じて歩幅を変更します。複数行のタイプライターにも同じことが当てはまり、通常、最後の行には特別な処理が必要です。