js字符串以键盘打字方式输出:

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了让字符串中的字符以键盘打字的方式输出。

代码非常的简单,上面也有足够的注释,不多做分析了,直接给出代码实例,如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>前端教程网</title>
<style type="text/css">
body{
  font-size:14px;
  font-color:#purple;
  font-weight:bolder;
}
</style>
<script>
var NewsTime = 2000;    //每条信息完整出现后停留时间
var TextTime = 100;    //每条信息中的字出现的间隔时间
    
var newsi = 0;
var txti = 0;
var txttimer;   //调用setInterval的返回值,用于取消对函数的周期性执行
var newstimer;
    
var newstitle = new Array();    //以数组形式保存每个信息的标题
var newshref = new Array();   //以数组形式保存信息标题的链接
    
newstitle[0] = "前端教程网欢迎您";   //显示在网页上的文字内容和对应的链接
newshref[0] = "http://www.pipipi.net";
    
newstitle[1] = "http://www.pipipi.net";
newshref[1] = "http://www.pipipi.net";
    
newstitle[2] = "蚂蚁特效欢迎您";
newshref[2] = "http://www.51texiao.cn";
    
newstitle[3] = "欢迎再来";
newshref[3] = "http://www.pipipi.net";
    
function shownew(){
  hwnewstr=newstitle[newsi];    //通过newsi传递,依次显示数组中的内容
  newslink=newshref[newsi];     //依次显示文字对应的链接
       
  if(txti>=hwnewstr.length){
    clearInterval(txttimer);  //一旦超过要显示的文字长度,清除对shownew()的周期性调用
    clearInterval(newstimer); 
    newsi++;   //显示数组中的下一个
        
    if(newsi>=newstitle.length){
      newsi = 0;  //当newsi大于信息标题的数量时,把newsi清零,重新从第一个显示
    }
    newstimer = setInterval("shownew()",NewsTime);   //间隔2000ms后重新调用shownew()
    txti = 0;  
    return;
  }
  clearInterval(txttimer);  
  document.getElementById("Hotnews").href = newslink;  
  document.getElementById("Hotnews").innerHTML = hwnewstr.substring(0,txti+1);   //截取字符,从第一个字符到txti+1个字符
      
  txti++;  //文字一个个出现
  txttimer = setInterval("shownew()",TextTime);   
}
 
window.onload=function(){
  shownew();
}
</script>
</head>
<body>
前端教程网公告:<a id = "Hotnews" href="" target="_blank"></a>
</body>
</html>

回复

我来回复
  • 暂无回复内容