I wanted to break the one string in the set of array elements. The output will be display with a time interval. Javascript:
<script type="text/javascript">
var caption= document.getElementById('caption');
var text=['Hey there please help me','solve the problem sleep BETTER.'];
function display(i){
if(i >= text.length){
i = 0;
}
caption.innerHTML = text[i];
setTimeout(function(){
display(i + 1)
}, 6000)
}
display(0)
</script>
The output is: solve the problem sleep BETTER. But I need something like this: solve the problem (In new line) sleep BETTER.
Html:
<div class= "content" >
h1><span id="caption"> </span></h1>
</div>
I need to display the caption with a new line.
Thank you!
Instead of simply overwriting the text content with caption.innerHTML = text[i]
, you'll want to append to the content with +=
. To output solve the problem
and sleep BETTER
onto new lines, you'll first want to separate and them out in the array, and then add an HTML line break ( <br />
) before outputting the new text:
var caption = document.getElementById('caption'); var text = ['Hey there please help me', 'solve the problem', 'sleep BETTER.']; function display(i) { if (i >= text.length) { i = 0; } caption.innerHTML += "<br />" + text[i]; setTimeout(function() { display(i + 1) }, 6000) } display(0)
<div class="content"> <h1><span id="caption"> </span></h1> </div>
If you don't want the to repeat, simply set the functionality inside of an if
statement that checks if (i < text.length)
:
var caption = document.getElementById('caption'); var text = ['Hey there please help me', 'solve the problem', 'sleep BETTER.']; function display(i) { if (i < text.length) { caption.innerHTML += "<br />" + text[i]; setTimeout(function() { display(i + 1) }, 6000) } } display(0)
<div class="content"> <h1><span id="caption"> </span></h1> </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.