首页 > 解决方案 > 使用 for 循环向页面动态添加字符串的问题

问题描述

我想使用 for 循环向页面动态添加三个句子。问题是Sentences数组中的所有句子在输出中彼此重叠,而不是新行中的每个句子。

这是到目前为止的代码:

let Sentences = [

'i was sent to earth to protect you.',

'they have been working around here.',

'just another example sentence.',

];


generateSentences();

function generateSentences() {

    for(let i = 0; i < Sentences.length; i++){

      let addSentence = document.getElementById(`Sentence${i}`);

      let sentence = '';
      sentence = `<span>${Sentences[i]}</span>`;
      addSentence.innerHTML = `${sentence}`;

    } // end of for loop
 
};
.container {
    position: absolute;
    overflow: hidden;
    left: 8.7vw;
    top: 25vh;
    height: 55vh;
    width: 82vw;   
    outline: 0.1vw dashed orange;
}

.main-class {
    position: absolute;
    white-space: pre-wrap; 
    font-family: 'Open Sans', sans-serif;  
    font-weight:400;
    color: #595959;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}

.Sentence-class1 {
    top: 0;
    left: 0;
    right: 0;
    bottom: 40;
}


.Sentence-class2 {
    top: 0;
    left: 0;
    right: 0;
    bottom: 20;
}

.Sentence-class3 {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
<div class="containerAnswering"> 

<div id="Sentence0" class="main-class Sentence-class1"></div>
<div id="Sentence1" class="main-class Sentence-class2"></div>
<div id="Sentence2" class="main-class Sentence-class3"></div>

</div>

标签: javascripthtmlcss

解决方案


您不需要将所有三个句子 div 居中,因为这会使它们相互重叠。相反,您使用如下所示的内容。

flex-direction: column此外,如果您希望每个句子出现在另一个下方,这将有所帮助。

此外,如果您需要句子之间的间距,您可以定义一个类,例如sentence并使用 CSSmargin来添加间距。

let Sentences = [

'i was sent to earth to protect you.',

'they have been working around here.',

'just another example sentence.',

];


generateSentences();

function generateSentences() {

    for(let i = 0; i < Sentences.length; i++){

      let addSentence = document.getElementById(`Sentence${i}`);

      let sentence = '';
      sentence = `<span>${Sentences[i]}</span>`;
      addSentence.innerHTML = `${sentence}`;

    } // end of for loop
 
};
.container {
    position: absolute;
    overflow: hidden;
    left: 8.7vw;
    top: 25vh;
    height: 55vh;
    width: 82vw;   
    outline: 0.1vw dashed orange;
}

.main-class {
    position: absolute;
    white-space: pre-wrap; 
    font-family: 'Open Sans', sans-serif;  
    font-weight:400;
    color: #595959;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.sentence {
  margin: 8px 0;
}
<div class="containerAnswering"> 

<div class="main-class">
  <div id="Sentence0" class="sentence"></div>
  <div id="Sentence1" class="sentence"></div>
  <div id="Sentence2" class="sentence"></div>
</div>
</div>


推荐阅读