我想制作一个具有打字机效果的组件,但我需要将样式保留在插槽内,以便我可以使用具有相同效果的任何文本样式。
主文件:
<TypewriterText>
<h1>Hey what's up!</h1>
</TypewriterText>
TypewriterText.svelte:
<script>
import { onMount } from 'svelte';
let content = '';
let currentText = '';
let currentIndex = 0;
onMount(() => {
const data = document.querySelector('.hidden');
content = data?.innerText || '';
typeWriter();
});
function typeWriter() {
if (currentIndex < content.length) {
currentText += content.charAt(currentIndex);
currentIndex++;
setTimeout(typeWriter, 10);
}
}
</script>
<span class="hidden"><slot /></span>
{currentText}
<style>
.hidden {
display: none;
}
</style>
我发现的唯一方法是隐藏插槽并重现下面的内部文本。但这样我就失去了 html 标签...
非常感谢!!
难道不能只是一个行动吗?
<script>
const typewriter = node => {
let timeout = undefined;
const fullText = node.textContent;
node.textContent = '';
type();
function type() {
if (node.textContent.length >= fullText.length)
return;
node.textContent = fullText.substring(0, node.textContent.length + 1);
timeout = setTimeout(type, 100);
}
return { destroy() { clearTimeout(timeout); } }
}
</script>
<h1 use:typewriter>Hello there</h1>