作为计算机业余爱好者,把网页做得美观高大上对我是一种折磨和挑战,所以我做出来的网页都是清一色的word文档风格。为了给low逼的网页提升点儿逼格,我决定模仿一下ChatGPT的文字输出效果。
先上效果图:
以下是完整代码:
加粗文本-Bold Text
斜体文本-Italic Text
下划线文本-Underline Text
红色文本-Red Text
大字体文本-Large Text
链接示例-Link Example
这段代码中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Typing Effect</title>
<style>
#output {
display: inline;
}
.cursor {
display: inline-block;
width: 10px;
height: 20px;
background-color: black;
vertical-align: text-bottom;
animation: blink 1s infinite;
}
@keyframes blink {
50% {
opacity: 0;
}
}
</style>
</head>
<body>
<h1>ChatGPT Typing Effect</h1>
<div id="output"></div><span class="cursor" id="cursor"></span>
<div id="givenText" style="display: none;">
<strong>加粗文本-Bold Text</strong><br>
<em>斜体文本-Italic Text</em><br>
<u>下划线文本-Underline Text</u><br>
<span style="color: red;">红色文本-Red Text</span><br>
<span style="font-size: 24px;">大字体文本-Large Text</span><br>
<a href="https://github.com/">链接示例-Link Example</a>
</div>
<script>
const outputElement = document.getElementById("output");
const cursorElement = document.getElementById("cursor");
const givenTextElement = document.getElementById("givenText");
const givenText = givenTextElement.innerHTML;
let currentIndex = 0;
let currentHTML = "";
function typeText() {
if (currentIndex < givenText.length) {
const currentChar = givenText.charAt(currentIndex);
if (currentChar === "<") {
const closingTagIndex = givenText.indexOf(">", currentIndex);
currentHTML += givenText.slice(currentIndex, closingTagIndex + 1);
currentIndex = closingTagIndex + 1;
} else {
currentHTML += currentChar;
currentIndex++;
}
outputElement.innerHTML = currentHTML;
setTimeout(typeText, 100); // 设置打字速度,单位为毫秒
} else {
// 当打印完成时,移除光标的闪烁效果
cursorElement.classList.remove("cursor");
}
}
typeText();
</script>
</body>
</html>
(1)用于显示输出文本内容。
(2)用于显示闪烁的光标。
(3)中通过CSS控制光标闪烁的效果。
(4)中通过javascript控制文字的输出。
(5)中的内容不会显示,只用于向javascript中的givenTextElement变量赋值。
(6)文字输出的效果是通过拆分givenTextElement变量中的内容向currentHTML变量传递,然后使用innerHTML方法以覆盖显示的方式不断输出显示。
(7)可以通过修改setTimeout(typeText, 100)来控制文字输出的速度。
(8)这段代码只是在实现了与ChatGPT相似的视觉效果,但是原理与ChatGPT并不相同。
这段代码需要提前获取需要显示的全部文本内容,然后逐渐输出显示;而ChatGPT则使用了类似stream传输的技术,并不依赖于提前获取需要显示的全部文本内容。
6 天前