使用js的setInterval實現網頁打字機效果

練習用jquery寫打字機的效果。

  1. var typingText="放一段文字在這裡,讓它像打字機一樣一個一個的打出來,顯示出來";   
  2. var count=0;   
  3. var $myBlock=$("#myDiv");   
  4.   
  5. function type(){   
  6.     if(count<=typingText.length){   
  7.         $myBlock.html(typingText.substring(0, count));   
  8.         count++;   
  9.     }else{   
  10.         window.clearInterval(typewriter);      
  11.     }   
  12. }   
  13. var typewriter=window.setInterval(type ,200);  

setInterval的應用跟clearInterval,之前寫的東西就是沒有clearInterval,會浪費效能。

Demo

留言