js打字效果——感谢

HTML:

<div id="typedtext"></div>

js为:

var aText = new Array(
"让我怎样感谢你", 
"当我走向你的时候", 
"我原想收获一缕春风", 
"你却给了我整个春天",
"", 
"让我怎样感谢你", 
"当我走向你的时候", 
"我原想捧起一簇浪花", 
"你却给了我整个海洋 ", 
"", 
"让我怎样感谢你", 
"当我走向你的时候 ", 
"我原想撷取一枚红叶 ", 
"你却给了我整个枫林 ", 
"", 
"让我怎样感谢你", 
"当我走向你的时候", 
"我原想亲吻一朵雪花", 
"你却给了我银色的世界"
);
var iSpeed = 100; // time delay of print out  值越大速度越慢
var iIndex = 0; // 输入的起始位置
var iArrLength = aText[0].length; // the length of the text array 数组中第一个字符串的长度
var iScrollAt = 20; // start scrolling up at this many lines  可以显示的最多行数
 
var iTextPos = 0; // initialise text position 初始化文字的位置
var sContents = ''; // initialise contents variable 
var iRow; // initialise current row 初始化现在的行数
function typewriter()
{
 sContents =  ' ';
 iRow = Math.max(0, iIndex-iScrollAt); //来返回指定数字中带有最高值的数字。

 var destination = document.getElementById("typedtext");//获取元素
 
 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '<br />';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_"; //substring() 方法用于提取字符串中介于两个指定下标之间的字符。
 if ( iTextPos++ == iArrLength ) { //当字符串写完的时候
  iTextPos = 0;//
  iIndex++;  //
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length; //第iIndex个字符串的长度
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}

typewriter();

展示为:

原文地址:https://www.cnblogs.com/cacti/p/4600098.html