Home > Software engineering >  How to make line-by-line text appearance?
How to make line-by-line text appearance?

Time:10-07

I need to make line-by-line text appearance I think I have to split the text into lines and wrap each line in span.

Before:

<p>qwerty321<br>
qwerty321<br>
qwerty321<br></p>

After:

<p><span>qwerty321<br></span>
<span>qwerty321<br></span>
<span>qwerty321<br></span></p>

I think it should be like this. But I don't know how to do this. Vanilla JS

Edit: Sorry but I wrote the problem incorrectly. Look, I have some text(text in the question is just example) and I have to show it line-by-line while scrolling. That's the problem. And I don't think that I can use CSS only

CodePudding user response:

You don't have to use Javascript for this. You can do it with CSS using animation, opacity and by selecting each element with the nth-child selector:

@keyframes fadeIn {
  100% {
    opacity: 1;
  }
}

.fade {
  animation: fadeIn .5s forwards;
  opacity: 0;
}

.fade:nth-child(1) {
  animation-delay: .5s;
}

.fade:nth-child(2) {
  animation-delay: 1s;
}

.fade:nth-child(3) {
  animation-delay: 1.5s;
}
<div class="fade">qwerty321</div>
<div class="fade">qwerty321</div>
<div class="fade">qwerty321</div>

CodePudding user response:

You can make a wrapper function that creates a span and adds the elements to it.

var wrap2 = function (node1, node2) {
    const wrapper = document.createElement('span');
    node1.parentNode.appendChild(wrapper);
    wrapper.appendChild(node1);
    wrapper.appendChild(node2);
};

var p = document.querySelector("p");
var nodes = Array.from(p.childNodes);
for (var i=0; i<nodes.length; i =2) {
  wrap2(nodes[i], nodes[i 1]);
}
span { background-color: yellow; }
<p>a1<br>
a2<br>
a3<br></p>

  • Related