在这个示例中,我们首先在HTML中定义了一个div元素,并在其中添加了一个p元素以及伪类,分别用于显示打印的文本和光标。在CSS中,我们设置了打印文本和光标的样式,并定义了光标闪烁的动画。
在Javascript中,我们首先获取了打印文本元素,并定义了要打印的文本和每个字符打印的时间间隔和光标闪烁的时间间隔。
接着,我们定义了一个type函数,用于实现打印文本和移动光标的效果。在该函数中,我们首先计算出应该打印的文本,并更新显示的文本。然后判断是否打印完所有文本,如果没有则继续打印。
最后,在全局作用域中,我们定义了一个typingIndex变量用于记录已经打印的字符数,并计算出每个字符的,代码如下:
HTML
<div id="typing-container">
<p id="typing"></p>
</div>
CSS
#typing {
display: inline-block;
white-space: nowrap;
overflow: hidden;
font-size: 24px;
line-height: 1.5;
}
#typing::after{
content: '|';
animation: blink 0.8s infinite;
padding-left: 5px;
}
@keyframes blink {
50% {
opacity: 0;
}
}
JS
const typingElement = document.getElementById("typing");
const text = "This is an example of typing animation.";
const typingDelay = 50; // 每个字符打印的时间间隔
const cursorDelay = 500; // 光标闪烁的时间间隔
function type() {
// 计算出应该打印的文本
const currentText = text.slice(0, typingIndex);
// 更新显示的文本和光标位置
typingElement.textContent = currentText;
// 如果还没打印完所有文本,则继续打印
if (typingIndex < text.length) {
typingIndex++;
setTimeout(type, typingDelay);
}
}
let typingIndex = 0;
const charWidth = typingElement.getBoundingClientRect().width / text.length;
// 等待一段时间,让用户有时间看到光标
setTimeout(type, cursorDelay);