<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字打字机效果</title>
<style>
.text-block {
width: 80%;
height: 45px;
/* border: 1px solid #000; */
white-space: pre-wrap;
overflow: hidden;
}
.text {
white-space: pre;
overflow: hidden;
/* border-right: .15em solid orange; */
animation:
typing 3s steps(50, end),
blink-caret .75s step-end infinite;
}
@keyframes typing {
from {
width: 0;
}
to {
width: 100%;
}
}
@keyframes blink-caret {
from, to {
/* border-color: transparent; */
}
50% {
/* border-color: orange; */
}
}
</style>
</head>
<body>
<div id="box">
<div class="text-block" id="textBlock">
<p class="text"></p>
</div>
</div>
<script>
let Timer = null
const allText = "友谊是人类生活中最珍贵的财富之一,它是一种理解、支持和真诚的情感纽带。在我们的成长历程中,友谊扮演着重要的角色,给予我们力量和勇气,让我们在人生的旅途中不再感到孤独。友谊的种子可以在任何时刻、任何地点种下。在校园里,同学之间的友谊如同一缕清风,在繁忙的学习生活中给予彼此慰藉和帮助;在职场上,同事之间的友谊如同一把温暖的火炉,在工作中互相支持鼓励;在生活中,朋友之间的友谊如同一本永不完结的故事书,记录着彼此的欢笑、泪水和成长。友谊不仅仅存在于美好的时更困难的时刻展现出其真正的力量。当我们遇到挫折和困境时,朋友们伸出援手,给予我们坚定的支持和无限的鼓励。他们在我们最需要的时候从心底给予关怀和帮助,让我们感受到无与伦比的温暖和力量。正是因为友谊的存在,我们才能勇敢面对挑战,超越困难,不断前行。友谊的力量是无以伦比的,它能够点燃希望的火焰,温暖寒冷的心灵,让生活充满阳光和色彩。在友谊的世界里,我们可以不假装成谁,可以毫无保留地展现自己的真实和脆弱,因为我们知道,真正的友谊能够包容一切,包括我们的缺点和不足。让我们珍惜身边的每一个友谊,用心去呵护、用行动去诠释。因为友谊不仅是一种情感,更是一种责任和承诺。让友谊之花永远绽放,在生命的征途中永不凋零。"
function startTyping(i = 0) {
const text = allText.substring(i * 30, i * 30 + 30)
if (text.length < 30) {
clearInterval(Timer)
}
let textElement = document.getElementsByClassName('text')[i]
document.getElementsByClassName('text')[i].textContent = text
let animationDuration = 0;
// for (let i = 0; i < text.length; i++) {
// const char = text.charAt(i);
// const delay = 50 * i;
// animationDuration = delay + 500; // 500 is the duration of the typing animation
// setTimeout(function() {
// textElement.textContent += char;
// if (i === text.length - 1) {
// textElement.dispatchEvent(new Event('animation-complete'));
// }
// }, delay);
// }
// textElement.addEventListener('animation-complete', function() {
// // Animation complete, do something here
// console.log('The first line is fully displayed.');
// // startTyping()
// });
}
function insertTypingEffect() {
const targetNode = document.getElementById('box');
const textBlock = document.createElement('div');
textBlock.classList.add('text-block');
textBlock.id = 'textBlock';
const paragraph = document.createElement('p');
paragraph.classList.add('text');
textBlock.appendChild(paragraph);
targetNode.appendChild(textBlock);
let i = document.getElementsByClassName('text').length - 1
startTyping(i);
}
Timer = setInterval(() => {
insertTypingEffect()
}, 900)
</script>
</body>
</html>