0

我有以下功能:

var index = 0;
var text = 'Hello world!';
function type() {
  document.getElementById('screen').innerHTML += text.charAt(index);
  index += 1;
  var t = setTimeout('type()',200);
}

我想知道是否可以让它在单词 hello 和 world 之间添加一个 br 标签。

我试过这样:'hello' + br tag + 'world'; 但没有奏效,可能是因为charAt。

谢谢

4

1 回答 1

1

一种可能的方法:

var index = 0;
var text = 'Hello world!';
var textLength = text.length;
var elScreen = document.getElementById('screen');
(function type() {
  var charToType = text.charAt(index);
  if (charToType === ' ') {
    charToType = '<br />';
  }
  elScreen.innerHTML += charToType;
  index += 1;
  if (index < textLength) {
    setTimeout(type, 200);
  }
})();

演示。关键思想很简单:当接下来要处理的字符是空格时,它被替换为<br />.

注意这里的另外两个变化:

  • 可以使用函数引用(而不是字符串)作为 setTimeout 第一个参数。实际上,应该以这种方式使用它。

  • 除非有很大的理由这样做,否则应该在到达结尾时停止“键入”该字符串 - 因此进行index < textLength检查。

于 2014-04-30T16:16:15.543 回答