我尝试创建动画打字/删除效果。它确实会打字,但当它完成第一句话时,它不会做任何其他事情。看起来它被困在第一个 if 语句中。
window.onload = () => {
const sentences = ['Who am I?', 'Who are you?', 'Who are we?'];
const input = document.getElementsByName('q')[0];
let sentence = 0;
let character = 0;
let typing = true;
(function typing() {
if (character === sentences[sentence].length - 1) {
typing = false;
} else if (character === 0) {
if (sentence < sentences.length - 1) {
sentence++;
} else {
sentence = 0
}
typing = true;
}
if (typing) {
character++;
} else {
character--;
}
input.placeholder = sentences[sentence].substring(0, character);
setTimeout(typing, ~~(Math.random() * (300 - 60 + 1) + 60));
})();
};
最佳答案
您在函数本身中重写函数,setTimeout
接收一个 bool 值作为第一个参数
对于函数名称,最好使用像 typeSentence
这样的动词
对于 bool 值,最好使用像 isTyping
关于javascript - native JavaScript 中的动画输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38305952/