首页 > 解决方案 > 我需要整个类型的文字在第二个循环消失之前在页面上停留一段时间

问题描述

1 . 一旦在第二个循环之前完全写入,我需要整个类型的书写文本留在显示屏上。请在我的代码上应用解决方案。

2 . 其次,在我的文本字符串中,当我使用“b”或“strong”标签将特定文本变为粗体时,在键入过程中会显示“<”符号几毫秒,所有其他标签都会发生同样的事情。我不知道我的代码有什么问题。

下面是我的代码。

for (let i = 0; i < 10; i++) {
  task(i);
}

function task(i) {
  setTimeout(function() {
    // Add tasks to do 
    var typeString = ['• I m Mr.Frits.\n• and   I <b>love </b> Pakistan...:)'];
    var i = 0;
    var count = 0
    var selectedText = '';
    var text = '';
    
    (function type() {
      if (count == typeString.length) {
        count = 0;
      }

      selectedText = typeString[count];
      text = selectedText.slice(0, ++i);
      document.getElementById('typing').innerHTML = text.fontsize(6);
      document.getElementById('typing').style.fontFamily = "monospace";
      document.getElementById("typing").style.color = "black";
      document.getElementById("typing").style.fontWeight = "normal";

      if (text.length === selectedText.length) {
        count++;
        i = 0;
      }

      /* SOLUTION : wait two seconds when new line */
      if (typeString[0][i - 1] == '\n') {
        setTimeout(type, 1000);
      } else {
        setTimeout(type, 100);
      }
    }());
  }, 1000);
}
<pre id="typing"></pre>

标签: javascripthtmlcss

解决方案


由于 count 设置为1一旦达到字符串末尾的长度,您可以添加条件并在满足时增加超时:

/* SOLUTION : wait two seconds when new line */
if (typeString[0][i - 1] == '\n') {
    setTimeout(type, 1000);
} else if (count === 1) {
    setTimeout(type, 3000);
} else {
    setTimeout(type, 100);
}

使用<br />'s,浏览器在标记完成之前不会将其注册为有效的 HTML。因此,有那么一秒钟,所有呈现的内容都<在标记的其余部分完成之前,并且它了解该标记是什么。

for (let i = 0; i < 10; i++) {
  task(i);
}

function task(i) {
  setTimeout(function() {
    // Add tasks to do 
    var typeString = ['• I m Mr.Frits.\n• and   I love  Pakistan...:)'];
    var i = 0;
    var count = 0;
    var selectedText = '';
    var text = '';
    var typing = document.getElementById('typing');

    (function type() {
      if (count == typeString.length) {
        count = 0;
      };

      selectedText = typeString[count];
      text = selectedText.slice(0, ++i);
      typing.innerHTML = text.fontsize(6);
      typing.style.fontFamily = "monospace";
      typing.style.color = "black";
      typing.style.fontWeight = "normal";

      if (text.length === selectedText.length) {
        count++;
        i = 0;
      }

      /* SOLUTION : wait two seconds when new line */
      if (typeString[0][i - 1] == '\n') {
        setTimeout(type, 1000);
      } else if (count === 1) {
        setTimeout(type, 3000);
      } else {
        setTimeout(type, 100);
      }
    }());
  }, 1000);
}
<pre id="typing"></pre>


推荐阅读