我想使用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>
答案 0 :(得分:0)
您不需要将所有三个句子div居中,因为这会使它们彼此重叠。相反,您可以使用类似下面的内容。
此外,如果您希望每个句子中的一个出现在另一个之下,则使用flex-direction: column
会有所帮助。
此外,如果句子之间需要空格,则可以定义一个类,例如sentence
并使用CSS margin
添加空格。
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>
答案 1 :(得分:0)
您遇到的主要问题是,您没有为css“底部”属性提供单位,例如px,rem等。除0以外的任何值都需要指定一个显式单位,具体取决于浏览器。例如:
.Sentence-class1 {
top: 0;
left: 0;
right: 0;
bottom: 40px;
}
我也只想指出您的容器元素的类在HTML中是“ containerAnswering”,而在CSS中只是“ container”。除非也许您引用的是这里未显示的其他元素,否则我认为应该以防万一。