我有这样的打字机功能:



var myArray = [
  'sentence. another sentence.',
  'this sentence. yet another sentence.',
];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var i = 0;
var speed = 55;

function typeWriter() {
  if (i < rand.length) {
    document.getElementById("question").innerHTML += rand.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}

typeWriter();

<div id="question"></div>





如何使打字机功能速度更改为80毫秒,如果当前正在键入的字符是点号或逗号,然后在键入普通字母时返回55毫秒?这将有助于我通过键入功能来模仿语音节奏并提高可读性。谢谢你的帮助。

最佳答案

您已经有一个名为speed的变量,那么为什么当当前字符是逗号或点号时不更改其值呢? (不要忘记稍后再将其更改!)。



var myArray = ['sentence. another sentence.',
              'this sentence. yet another sentence.',
           ];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var i = 0;
var speed = 55;
  function typeWriter() {
    if (i < rand.length) {
      document.getElementById("question").innerHTML += rand.charAt(i);

    if(rand.charAt(i) == '.' || rand.charAt(i) == ',') {
      speed = 1000;
    }
    else {
      speed = 85;
    }
    i++;
    setTimeout(typeWriter, speed);
  }
}

typeWriter();

<p id="question"></p>

关于javascript - 当遇到句点或逗号时,如何减慢从数组中键入随机字符串的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58511238/

10-14 22:48