【发布时间】:2022-11-03 00:28:01
【问题描述】:
我有一个脚本,以某种打字机样式显示存储在文本数组中的多个单词。但是,脚本在输入几个条目后停止,并且没有按预期遍历数组中的所有单词。也许我看不到明显的问题,但是请给我一个提示吗?
这是它的一支笔: https://codepen.io/jackennils/pen/KKeVEbJ
document.addEventListener('DOMContentLoaded', function(event) {
// array with texts to type in typewriter
var dataText = ["Holz", "Schiefer", "Jeans", "Edelstahl", "Spiegel", "Acryl", "Leder", "Kork", "Fliesen", "Stein"];
// type one text in the typwriter
// keeps calling itself until the text is finished
function typeWriter(text, i, fnCallback) {
// check if text isn't finished yet
if (i < (text.length)) {
// add next character to span
document.querySelector("span.mats").innerHTML = text.substring(0, i + 1) + '<span class="mats-inner" aria-hidden="true"></span>';
// wait for a while and call this function again for next character
setTimeout(function() {
typeWriter(text, i + 1, fnCallback)
}, 100);
}
// text finished, call callback if there is a callback function
else if (typeof fnCallback == 'function') {
// call callback after timeout
setTimeout(fnCallback, 1000);
}
}
// start a typewriter animation for a text in the dataText array
function StartTextAnimation(i) {
if (typeof dataText[i] == 'undefined') {
setTimeout(function() {
StartTextAnimation(0);
}, 0);
}
// check if dataText[i] exists
if (i < dataText[i].length) {
// text exists! start typewriter animation
typeWriter(dataText[i], 0, function() {
// after callback (and whole text has been animated), start next text
StartTextAnimation(i + 1);
});
}
}
// start the text animation
StartTextAnimation(0);
});
body {
background-color: #362871;
height: 100%;
font-family: 'Raleway', sans-serif;
}
p {
font-size: 5em;
color: white;
text-transform: uppercase;
}
span.mats-inner {
border-right: 20px solid;
margin-left: 10px;
animation: caret 1s steps(1) infinite;
}
@keyframes caret {
50% {
border-color: transparent;
}
}
<p>Wir veredeln <span class="mats">mit Licht</span></p>
【问题讨论】:
标签: javascript arrays animation text