javascript - 使用 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>
解决方案
您不需要将所有三个句子 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>
推荐阅读
- postgresql - PostgreSQL 用 CASE 语句选择 INTO
- iis - iis如何使用saml2.0访问adfs
- apache-spark - Spark RDD saveAsTextFile 给出 java.io.IOException: Mkdirs failed to create
- shopify - 如何在 Shopify 中进行社交登录后登录或启动客户会话
- python - 从 Django ORM 中提取外连接
- node.js - 使用 Lambda 函数、NodeJS、Mailgun 发送电子邮件并在 Postman 中测试参数
- java - 在 Java 中处理多个用户输入
- java - 当文本部分为空白并且按钮被按下时(在 android studio 中),如何显示 toast 消息?
- php - 如何将条件附加到雄辩的关系查询?
- python - 看起来像 b'\x1f\x8b\.....' 的文件格式到底是什么