首頁  >  文章  >  web前端  >  介紹一個javascript 實現文字打字效果的特效實例

介紹一個javascript 實現文字打字效果的特效實例

伊谢尔伦
伊谢尔伦原創
2017-04-29 14:53:081757瀏覽

本章節主要介紹在瀏覽網頁的時候也常常能看到文字實現打字的效果,本節程式碼主要使用了 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