前端 AI 类产品(如 ChatGPT、文心一言等)中常见的“打字机效果”(逐字显示文本)是一种用户体验优化技术,旨在模拟人类打字的过程,增强交互的自然感和流畅性。以下是实现打字机效果的原理和常见方法:
1. 实现原理
打字机效果的核心是通过 JavaScript 动态控制文本的显示,逐字或逐段地将内容添加到页面上。具体步骤如下:
-
获取文本内容
:从服务器或本地获取需要显示的文本。
-
逐字显示
:通过定时器(如
setTimeout
或
setInterval
)逐字将文本添加到 DOM 元素中。
-
-
结束处理
:当文本完全显示后,停止定时器并触发回调(如显示光标闪烁或执行下一步操作)。
2. 实现方法
以下是几种常见的实现方式:
方法 1:使用
setTimeout
递归实现
function typeWriter(element, text, speed = 100) {
let i = 0;
function type(
) {
if (i < text.length) {
element.textContent += text.charAt(i); // 逐字添加到 DOM
i++;
setTimeout(type, speed); // 递归调用
}
}
type(); // 启动打字效果
}
// 使用示例
const outputElement = document.getElementById("output");
typeWriter(outputElement, "Hello, world!", 100);
方法 2:使用
setInterval
实现
function typeWriter(element, text, speed = 100) {
let i = 0;
const timer = setInterval(() => {
if (i < text.length) {
element.textContent += text.charAt(i); // 逐字添加到 DOM
i++;
} else {
clearInterval(timer); // 停止定时器
}
}, speed);
}
// 使用示例
const outputElement = document.getElementById("output");
typeWriter(outputElement, "Hello, world!", 100);
方法 3:使用 CSS 动画(伪元素 +
steps
)
@keyframes typing {
from { width: 0; }
to { width: 100%; }
}
.typewriter {
overflow: hidden; /* 隐藏溢出内容 */
white-space: nowrap; /* 禁止换行 */
border-right: 2px solid; /* 模拟光标 */
animation: typing 3s steps(40, end); /* steps 控制逐字效果 */
}
<div class="typewriter">Hello, world!div>
方法 4:结合 AI 流式输出
在 AI 类产品中,打字机效果通常与流式输出结合使用。服务器通过流式传输(如 SSE 或 WebSocket)逐步返回生成的文本,前端逐字显示。
// 模拟流式输出
function simulateStreaming(element, text, speed = 100) {
let i = 0;
const timer = setInterval(() => {
if (i < text.length) {
element.textContent += text.charAt(i); // 逐字添加到 DOM
i++;
} else {
clearInterval(timer); // 停止定时器
}
}, speed);
}
// 使用示例
const outputElement = document.getElementById("output");
simulateStreaming(outputElement, "Hello, world!", 100);
3. 优化技巧
-
-
使用 CSS 实现闪烁的光标:
.cursor {
display: inline-block;
width: 2px;
height: 1em;
background-color: black;
animation: blink 1s steps(2, start) infinite;
}
@keyframes blink {
to { visibility: hidden; }
}
-
在打字结束后显示光标:
function typeWriter(element, text, speed = 100) {
let i = 0;
function type(
) {
if (i < text.length) {
element.textContent += text.charAt(i);
i++;
setTimeout(type, speed);
} else {
element.innerHTML += ''; // 添加光标
}
}
type();
}
-
如果文本包含换行符(
\n
),可以使用
替换:
element.innerHTML += text.charAt(i) === "\n" ? "
" : text.charAt(i);
-
根据文本长度或用户设置动态调整打字速度:
const speed = Math.max(50, 200 - text.length * 2); // 文本越长,速度越快
-
使用
clearTimeout
或
clearInterval
实现暂停,保存当前状态以便继续。
4. 实际应用场景
-
AI 对话
:逐字显示 AI 生成的回复,增强交互的自然感。
-