1. 程式人生 > >用js實現打字機效果

用js實現打字機效果

1.難得有點時間,回憶下古詩文,順便練習下js,實現下打字機效果

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>打字機</title>
	<script type="text/javascript" src="text.js"></script>
</head>
<body>	
		<div id="myContent"></div>
		<div id="contentToWrite" style="display:none;">
		春江花月夜<br>張若虛 唐<br>
		春江潮水連海平,海上明月共潮生。<br>灩灩隨波千萬裡,何處春江無月明!<br>
		江流宛轉繞芳甸,月照花林皆似霰;<br>空裡流霜不覺飛,汀上白沙看不見。<br>
	       	江天一色無纖塵,皎皎空中孤月輪。<br>江畔何人初見月?江月何年初照人?<br>
	       	人生代代無窮已,江月年年只相似。<br>不知江月待何人,但見長江送流水。<br>
	       	白雲一片去悠悠,青楓浦上不勝愁。<br>誰家今夜扁舟子?何處相思明月樓?<br>
	       	可憐樓上月徘徊,應照離人妝鏡臺。<br>玉戶簾中卷不去,搗衣砧上拂還來。<br>
	       	此時相望不相聞,願逐月華流照君。<br>鴻雁長飛光不度,魚龍潛躍水成文。<br>
	       	昨夜閒潭夢落花,可憐春半不還家。<br>江水流春去欲盡,江潭落月復西斜。<br>
	       	斜月沉沉藏海霧,碣石瀟湘無限路。<br>不知乘月幾人歸,落月搖情滿江樹。<br>
		</div>
		<script type="text/javascript">
			writeContent(true);	
		</script>	
</body>
</html>

html程式碼就是要打的 內容,主要實現是js程式碼,如下:

var charIndex = -1;
var stringLength = 0;
var inputText;
function writeContent(init){
	if(init){
		inputText = document.getElementById('contentToWrite').innerHTML;
	}
	if(charIndex==-1){
		charIndex = 0;
		stringLength = inputText.length;
	}
	var initString = document.getElementById('myContent').innerHTML;
	initString = initString.replace(/<SPAN.*$/gi,"");

	var theChar = inputText.charAt(charIndex);
	var nextFourChars = inputText.substr(charIndex,4);
	if(nextFourChars=='<BR>' || nextFourChars=='<br>'){
		theChar  = '<BR>';
		charIndex+=3;
	}
	initString = initString + theChar + "<SPAN id='blink'>_</SPAN>";
	document.getElementById('myContent').innerHTML = initString;

	charIndex = charIndex/1 +1;
	if(charIndex%2==1){
		document.getElementById('blink').style.display='none';
	}else{
		document.getElementById('blink').style.display='inline';
	}

	if(charIndex<=stringLength){
		setTimeout('writeContent(false)',140);
	}else{
		blinkSpan();
	}  
}

var currentStyle = 'inline';
function blinkSpan(){
	if(currentStyle=='inline'){
		currentStyle='none';
	}else{
		currentStyle='inline';
	}
	document.getElementById('blink').style.display = currentStyle;
	setTimeout('blinkSpan()',100);
}