我试图复制键入效果,该效果在数组中循环并“键入”每个字符串。我设法使效果良好,但是我发现,如果当前的标语比数组中的下一个短,它将超出其较长的字符长度,并从下一项输出其余的缺少字符。 / p>
我可能解释得很差,但是如果有人想测试一下,您就会明白我的意思。
我知道问题与tagCount的递增位置和使用位置有关,但这只是我一直盯着一个小时却一无所获的那些事情之一。
var tagline = ['This is a tagline', 'Test string', 'Another test string', 'test'];
var tagCount = 0;
var output = document.getElementById('output');
var i = 0;
var countup = true;
var delayBool = true;
var interval = setInterval(function(){
if ((i < tagline[tagCount].length) && (countup == true)){
output.innerHTML += tagline[tagCount].charAt(i);
i++; }
else if((i > 0) && (countup == false)){
output.innerHTML = output.innerHTML.substring(0, output.innerHTML.length - 1);
i--; }
else if((i == 0) && (countup == false)){
countup = true; }
else if((i == tagline[tagCount].length) && (delayBool == true)){
delay();
delayBool = false;
}
console.log(tagCount)
}, 50);
function delay(){
if (tagCount < tagline.length-1){
tagCount++; }
else{
tagCount = 0; }
var delayInterval = setInterval(function(){
countup = false;
delayBool = true;
clearInterval(delayInterval);
}, 2000);
}
这里只有一点点HTML
<h1 id=output></h1>
答案 0 :(得分:1)
您拥有的东西很好,但是您可以使用javascript的某些功能来帮助您实现所需的东西。
每当处理数组或字符串字符等时,最好使用循环和长度,这样就不会像上面那样遇到计数器问题。
下面我有大纲和评论来帮助您理解。 希望这对您有所帮助。
<html>
<body>
<h1 id='output'></h1>
<script>
// creating our own sleep function
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// use async to wait instead of using intervals
async function print_words () {
var tagline = ['This is a tagline', 'Test string', 'Another test string', 'test'];
var output = document.getElementById('output');
// tagline is an array so you can simplify it using a loop that way you dont have to woory about counters
for (counter in tagline) {
var line = tagline [counter]; // the lines in the list
// this will print the right characters and because it is a
// loop the couter will start at 0 for every tagline so you won't
// have that problem again
// use another counter to go through character by charavter
for (var pos = 0; pos < line.length; pos++) {
var character = line[pos];
output.innerHTML += character;
await sleep (50); // wait for 50 ms
}
await sleep (1000); // how long to wait to remove
// now we move in revers but this way we only use one line of code to display the erasing effect
for (var rev = output.innerHTML.length - 1; rev >= 0; rev--) {
output.innerHTML = output.innerHTML.slice(0, rev);
await sleep (50); // wait for 50 ms
}
await sleep (2000); // wait for 2 seconds
// clear the screen
output.innerHTML = '';
}
}
print_words ();
</script>
</body>
</html>