我想顺序对 HTML 元素执行操作(就像顺序打字机)
我阅读了这个问题,了解如何循环子节点。
但我也读到我们不能使用 forEach 进行异步操作。
这是迄今为止不等待一个序列启动下一个序列的代码。
<script>
const typewriter = (node) => {
var fullText = '';
node.childNodes.forEach(async (child) => {
if (child.nodeType === 1) {
fullText = child.textContent;
child.textContent = '';
await type(child, fullText);
}
});
function type(node, fullText) {
return new Promise((resolve) => {
if (node.textContent.length >= fullText.length) {
resolve();
return;
}
node.textContent = fullText.substring(0, node.textContent.length + 1);
var timeout = setTimeout(type, 100, node, fullText);
});
}
return {
destroy() {
clearTimeout(timeout);
}
};
};
</script>
<span use:typewriter><slot /></span>
注意:它是一个简洁的组件,但我不确定它与问题有关 谢谢!
切换到“for of”,它支持await而不是foreach。
const typewriter = async (node) => {
for (const child of node.childNodes) {
...
await type(child, fullText);
}
}