我想要断开数组元素集中的一个字符串。输出将以时间间隔显示。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>
输出结果是:解决问题,睡得更好。但我需要这样的东西:解决问题(在新的行)更好地睡眠。
Html:
<div class= "content" >
h1><span id="caption"> </span></h1>
</div>
我需要用一个新的行来显示标题。
谢谢!
发布于 2018-10-08 04:12:50
不是简单地使用caption.innerHTML = text[i]
覆盖文本内容,而是希望使用+=
将追加到内容中。要将solve the problem
和sleep BETTER
输出到新行上,首先需要在数组中将它们分开,然后在输出新文本之前添加一个HTML换行符(<br />
):
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 (i < text.length)
的if
语句中设置该功能
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>
https://stackoverflow.com/questions/52692399
复制相似问题