首页  >  文章  >  web前端  >  介绍一个javascript 实现文字打字效果的特效实例

介绍一个javascript 实现文字打字效果的特效实例

伊谢尔伦
伊谢尔伦原创
2017-04-29 14:53:081756浏览

本章节主要介绍在浏览网页的时候也经常能看到文字实现打字的效果,本节代码主要使用了 onMousedown 事件和 event.button 属性,主要功能和用法如下。 
  • setTimeout 方法,在执行时是在载入后延迟指定时间后,去执行一次表达式,仅执行一次。 
  • charAt 方法返回一个字符值,该字符位于指定索引位置。字符串中的第一个字符的索引为0,第二个的索引为1,等等。超出有效范围的索引值返回空字符串。 

<html> 
<head> 
<title>打字效果的文字特效</title> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<script language="Javascript"> 
var layers = document.layers; 
var style = document.all; 
var both = layers || style; 
var idme = 908601; 
if(layers) //如果不是ie浏览器 
{ 
layerRef = &#39;document.layers&#39;; 
styleRef = &#39;&#39;; 
} 
if(style) //如果是ie浏览器 
{ 
layerRef = &#39;document.all&#39;; 
styleRef = &#39;.style&#39;; 
} 
function writeOnText(obj, str) { //函数在页面上打印字符串 
if(layers) { 
with(document[obj]) { 
document.open(); 
document.write(str); //write方法打印字符串 
document.close(); 
} 
} 
if(style) eval(obj+&#39;.innerHTML = str&#39;); //使用innerHTML属性显示字符串 
} 
var dispStr = new Array("phpcn"); //字符串数组 
var overMe = 0; 
function txtTyper(str, idx, idObj, spObj, clr1,clr2, delay, plysnd) //函数:实现打字效果 
{ 
var tmp0 = tmp1 = &#39;&#39;, skip = 100; 
if(both && idx <= str.length) { 
if(str.charAt(idx) == &#39;<&#39;) { 
while(str.charAt(idx) != &#39;>&#39;) idx++; 
idx++; 
} 
if(str.charAt(idx) == &#39;&&#39; && str.charAt(idx+1) != &#39;&#39;) { 
while(str.charAt(idx) != &#39;;&#39;) idx++; 
idx++; 
} 
tmp0 = str.slice(0, idx); 
tmp1 = str.charAt(idx++); 
if(overMe==0 && plysnd==1) { 
if(navigator.plugins[0]) { 
if(navigator.plugins["LiveAudio"][0].type == "audio/basic" && navigator.javaEnabled()) { 
document.embeds[0].stop(); 
setTimeout("document.embeds[0].play(false)", 100); 
} 
} else if(document.all) { 
ding.Stop(); 
setTimeout("ding.Run()", 100); 
} 
overMe = 1; 
} else { 
overMe = 0; 
} 
writeOnText(idObj, "<span class="+spObj+"><font color=&#39;"+clr1+"&#39;>"+tmp0+"</font><font color=&#39;"+clr2+"&#39;>"+tmp1+"</font></span>"); 
//调用writeOnText函数将字符显示在网页上 
setTimeout("txtTyper(&#39;"+str+"&#39;, "+idx+", &#39;"+idObj+"&#39;, &#39;"+spObj+"&#39;, &#39;"+clr1+"&#39;, &#39;"+clr2+"&#39;, "+delay+", "+plysnd+")", delay); 
} 
} 
function init() 
{ 
txtTyper(dispStr[0], 0, &#39;tt10&#39;, &#39;ttll&#39;, &#39;#339933&#39;, &#39;#99FF33&#39;, 300, 0); //调用txtTyper函数开始打字 
} 
</script> 
</head> 
<body onLoad="init();"> 
<center> 
<h1>打字效果的文字特效</h1> 
<hr /> 
 
<div class="ttll" id="tt10"></div> 
</center> 
</body> 
</html>

运行该程序后,页面出现一个提示信息,然后逐个出现字符。如此逐个出现字符后,等待全部打印完毕即可停止打印。

源程序解读 
  (1)程序首先建立了一个层,其 ID 为 ttl0,便于以后调用。这个层用来显示打印的文字。 
  (2)程序在6c04bd5ca3fcae76e30b72ad730ca86d元素上添加 onLoad 事件,当整个页面载入完成以后,该事件被触发,调用 init() 事件处理函数,对该事件进行处理。 
  (3)在函数 txtTyper() 中,使用 charAt 方法得到字符串中的某个字符。使用 if 条件语句判断该字符是否满足尽头。满足条件后打印在页面上。 
  (4)在 if 语句中,也可使用任意合法的 Javascript 语句,完成更为复杂的操作。 

以上是介绍一个javascript 实现文字打字效果的特效实例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn