我有一个元素,其中数组中的文本逐行迭代,这很有效。
我希望文字出现在网页的中央,也是中间
我是 Javascript + HTMl 的新手
到目前为止,这是迭代数组中文本的代码。
var container = document.querySelector('#container');
var splittedText = [
"This is line one", "This is line two", "This is line three", "This is line four"
];
var clone = [...splittedText]
var content = []
var intervalId = setInterval(function() {
if (content.length >= 1) content = []
var element = clone.shift();
content.push(element + "<br/>");
if (clone[0] == "") {
content.push("<br/>");
clone.shift();
}
container.innerHTML = content.join('')
if (clone.length === 0) {
clone = [...splittedText]
content = []
}
}, 3000)
#container {
padding: 1em;
text-align: center;
font-size: 400%;
}
<div id="container"></div>
最佳答案
我们需要使用一些标签而不是松散的字符串,以便我们可以设置样式。我认为这应该让你开始:
const body = document.body;
const splittedText = [
"This is line one",
"This is line two",
"This is line three",
"This is line four"
];
let clone = [...splittedText];
setInterval(function() {
const elSpan = document.createElement("span");
const elBr = document.createElement("br");
if (clone.length === 0) {
clone = [...splittedText];
let child = body.lastElementChild;
while (child) {
body.removeChild(child);
child = body.lastElementChild;
}
}
const text = clone.shift();
elSpan.innerHTML = text;
body.appendChild(elSpan);
body.appendChild(elBr);
if (text == "") {
body.appendChild(elBr);
clone.shift();
}
}, 3000);
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
span {
font-size: 20px;
}
关于javascript - 将文本放在页面的中心和中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402871/