简体   繁体   中英

How to add text dynamically to marquee on html with javascript

I wonder how to add text marquee dynamically, I have tried to using marquee tags like this:

<marquee scrollamount="5" loop="infinite" id="paragraph"> This is sample of my marquee </marquee>

and I append text like this:

document.getElementById("paragraph").innerHTML += ' This is how I to append text';

It's working but the problem is when I append text to marquee the first animation not working properly (text from right to left not finish and start looping again), so marquee only running until text before it's append and loop and when animation start loop, then the marquee animation runs all text (text from right to left finish until its finish and disappear then loop again)

And I have also tried make marquee using keyframes like this:

 function AppendData(){ document.getElementById("marquee").innerHTML += 'This is how i append data to marquee'; }
 @keyframes marquee { 0% { text-indent: 100% } 100% { text-indent: -100% } } @-webkit-keyframes marquee { 0% { text-indent: 100% } 100% { text-indent: -100% } }.marquee { overflow: hidden; white-space: nowrap; animation: marquee 17s linear infinite; -webkit-animation: marquee 17s linear infinite; }.marquee:hover { -webkit-animation-play-state: paused; animation-play-state: paused; }
 <button onclick="AppendData()">Append Data</button> <p class="marquee" id="marquee">This is my marquee not using marquee tags but using the keyfames by css.</p>

but the problem is same with using marquee tags, because 100% { text-indent: -100% } not dynamic.

My question is how to make marquee runs dynamically until finish or disappear from left to right when I append text in the first running marquee?

This should work

 function AppendData(){ e = document.querySelector('.marquee'); document.querySelector("span").append("new data") }
 .marquee span { display: inline-block; white-space:nowrap; padding-left: 100%; will-change: transform; /* show the marquee just outside the paragraph */ animation: marquee 5s linear infinite; }.marquee span:hover { animation-play-state: paused } /* Make it move */ @keyframes marquee { 0% { transform: translate(0, 0); } 100% { transform: translate(-100%, 0); } } /* Respect user preferences about animations */ @media (prefers-reduced-motion: reduce) {.marquee { white-space: normal }.marquee span { animation: none; padding-left: 0; } }
 <button onclick="AppendData()">Append Data</button> <div class="marquee" style="overflow: show"> <span> This is my marquee not using marquee tags but using the keyfames by css. </span> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM