使用.querySelectorAll方法可以选择DOM中的所有匹配元素,并返回一个NodeList对象。要创建打字机效果,可以按照以下步骤进行操作:
<div id="typewriter"></div>
const text = document.querySelectorAll('p');
let index = 0;
function type() {
if (index < text.length) {
document.getElementById("typewriter").innerHTML += text[index].textContent;
index++;
setTimeout(type, 100); // 设置延迟时间,控制打字速度
}
}
type();
完整的代码示例:
<!DOCTYPE html>
<html>
<head>
<title>Typewriter Effect</title>
<style>
#typewriter {
font-family: monospace;
white-space: pre;
}
</style>
</head>
<body>
<div id="typewriter"></div>
<script>
const text = document.querySelectorAll('p');
let index = 0;
function type() {
if (index < text.length) {
document.getElementById("typewriter").innerHTML += text[index].textContent;
index++;
setTimeout(type, 100); // 设置延迟时间,控制打字速度
}
}
type();
</script>
</body>
</html>
这样,使用.querySelectorAll方法和JavaScript就可以创建一个简单的打字机效果。请注意,这只是一个基本的示例,可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云