Your code searches a string for spaces to split on with strText.split(" ");
. The spaces are then lost. To restore them, add them back when you reconstitute your string with the added spans with text.innerHTML += "<span>" + splitText[i] + "</span> ";
or text.innerHTML += "<span>" + splitText[i] + "</span> ";
const text = document.querySelector(".hello");
const strText = text.textContent;
const splitText = strText.split(" ");
text.textContent = "";
for (let i = 0; i < splitText.length; i++) {
text.innerHTML += "<span>" + splitText[i] + "</span> ";
}
let char = 0;
let timer = setInterval(onTick, 50);
function onTick() {
const span = text.querySelectorAll('span')[char];
span.classList.add('fade');
char++;
if (char === splitText.length) {
complete();
return;
}
}
function complete() {
clearInterval(timer);
timer = null;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: black;
}
h1 {
color: white;
font-size: 4rem;
font-family: sans-serif;
}
span {
opacity: 0;
transition: all 1s ease;
transform: translateY(50px);
display: inline-block;
}
span.fade {
opacity: 1;
color: red;
transform: translateY(0px);
}
<h1 class="hello">Testing 1 2 3</h1>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…