实现打字机效果
要实现打字机效果并减少 DOM 重绘以提高性能,可以使用 TypeScript 和 JavaScript 的 requestAnimationFrame 方法。requestAnimationFrame 方法允许在下一帧动画之前执行函数,以减少不必要的 DOM 重绘。以下是一个简单的示例:
首先,在 HTML 中创建一个容器用于显示打字机效果
1<!DOCTYPE html>
2<html>
3<head>
4 <style>
5 #typing-container {
6 white-space: nowrap; /* 防止文本换行 */
7 overflow: hidden; /* 隐藏文本溢出 */
8 border-right: 1px solid; /* 模拟光标闪烁 */
9 }
10 </style>
11</head>
12<body>
13 <div id=\"typing-container\"></div>
14</body>
15</html>
打字机函数
1function typeWithBlinkingCursor(text: string, containerId: string, delay: number) {
2 const typingContainer = document.getElementById(containerId);
3
4 if (!typingContainer) {
5 console.error(`Element with ID \"${containerId}\" not found.`);
6 return;
7 }
8
9 const lines = text.split(\"\n\"); // 拆分文本为多行
10
11 let currentLineIndex = 0;
12 let currentIndex = 0;
13 let isCursorVisible = true;
14 let requestID: number | null = null;
15
16 function toggleCursor() {
17 isCursorVisible = !isCursorVisible;
18 typingContainer.style.borderRightColor = isCursorVisible ? \"black\" : \"transparent\";
19 requestID = requestAnimationFrame(toggleCursor);
20 }
21
22 function typeText() {
23 if (currentLineIndex < lines.length) {
24 const line = lines[currentLineIndex];
25
26 if (currentIndex < line.length) {
27 typingContainer.textContent += line.charAt(currentIndex);
28 currentIndex++;
29 requestID = requestAnimationFrame(typeText);
30 } else {
31 // 换行并重置索引
32 typingContainer.innerHTML += \"<br>\";
33 currentLineIndex++;
34 currentIndex = 0;
35 requestID = requestAnimationFrame(typeText);
36 }
37 } else {
38 cancelAnimationFrame(requestID!);
39 }
40 }
41
42 setTimeout(() => {
43 toggleCursor();
44 typeText();
45 }, delay); // 添加延迟
46}
使用示例
1 typeWithBlinkingCursor(\"这是一个打字机效果的示例文本。\", \"typing-container\", 1000);
效果展示
下一篇:
ES6的一些高级技巧
相关笔记