不同的打字机效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>不同的打字机效果</title>
</head>
<body>
<button onclick="fn1()">方法1</button>
<button onclick="fn2()">方法2</button>
<button onclick="fn3()">方法3</button>
<button onclick="fn4()">方法4</button>
<div class="cont" id="cont"></div>
<script>
const text = document.querySelector('.cont');
let list = [
'<h1>部署</h1>',
'<span>首先,使用 npm run build 构建您的应用。</span>',
'<span style="color:red">这将在适配器选项中指定的输出目录(默认为 build)中创建生产服务端。</span>',
'<p>要运行应用程序,您需要输出目录、项目的 package.json 和 node_modules 中的生产依赖项。</p>',
'<p>生产依赖项可以通过复制 package.json 和 package-lock.json 然后运行 npm ci --omit dev 来生成(如果您的应用没有任何依赖项,可以跳过此步骤)。</p>'
]
function fn1() {
let index = -1;
text.innerHTML = '';
let timer = setInterval(() => {
if (index + 1 === list.length) {
clearInterval(timer)
timer = null;
return;
}
document.write(list[++index]);
}, 500);
}
function fn2() {
let index = -1;
text.innerHTML = '';
let timer = setInterval(() => {
if (index + 1 === list.length) {
clearInterval(timer)
timer = null;
return;
}
var newElement = document.createElement("p");
newElement.textContent = list[++index];
text.appendChild(newElement);
}, 500);
}
function fn3() {
let index = -1;
text.innerHTML = '';
let timer = setInterval(() => {
if (index + 1 === list.length) {
clearInterval(timer)
timer = null;
return;
}
text.insertAdjacentHTML('beforeend', list[++index])
timer = null;
}, 500);
}
let result = ''
function fn4() {
let tasks = list.map(item => () => type(item))
tasks.reduce((acc, task) => acc.then(task), Promise.resolve()).then(() => {
console.log('done')
});
}
function type(text) {
return new Promise((resolve) => {
let index = 0;
function next() {
if (text && index < text.length) {
document.getElementById('cont').innerHTML += text.charAt(index);
result += text.charAt(index);
index++;
setTimeout(next, 20);
} else {
document.getElementById('cont').innerHTML = result;
index = 0;
resolve();
}
}
next()
})
}
</script>
</body>
</html>