<!DOCTYPE html>
<html>
<head>
<style>
.container {
font-family: 'Courier New', monospace;
width: 600px;
min-height: 200px;
border: 1px solid #ccc;
padding: 20px;
line-height: 1.5;
}
#content {
white-space: pre-wrap;
word-break: break-word;
position: relative;
color: #333;
}
.cursor {
display: inline-block;
width: 10px;
height: 20px;
background: #333;
animation: blink 1s step-end infinite;
margin-left: 2px;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
</style>
</head>
<body>
<div class="container">
<div id="content"></div>
</div>
<script>
function typeWriter(text, speed = 50) {
const container = document.getElementById('content');
const cursor = document.createElement('span');
cursor.className = 'cursor';
container.appendChild(cursor);
let index = 0;
let currentLineWidth = 0;
const maxWidth = 600; // 容器宽度 - padding
function type() {
if (index >= text.length) {
cursor.remove();
return;
}
const char = text[index++];
const span = document.createElement('span');
span.textContent = char;
// 测量字符宽度
container.insertBefore(span, cursor);
const charWidth = span.getBoundingClientRect().width;
// 自动换行处理
if (currentLineWidth + charWidth > maxWidth || char === '\n') {
container.insertBefore(document.createElement('br'), cursor);
currentLineWidth = 0;
if (char === '\n') return type();
}
if (char !== '\n') {
currentLineWidth += charWidth;
}
// 保持光标可见
container.scrollTop = container.scrollHeight;
setTimeout(type, char === '\n' ? speed * 2 : speed);
}
// 初始调用
setTimeout(type, speed);
}
// 示例文本(包含换行符)
const sampleText = "这是一个模拟自动换行和打字效果的示例文本。\n我们可以在这里添加多行内容,比如:\n1. 第一项内容\n2. 第二项内容\n3. 第三项内容...";
typeWriter(sampleText, 30);
</script>
</body>
</html>