在使用PPT时,有人会将文字做成逐字出现的动画效果,那么如何在网页上实现同样效果呢?其实就是采用定时器的方法。
如下代码所示:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
window.onload=function(){
var story = document.getElementById('word');
var s = document.getElementById('show');
var i = 0;
timer=setInterval(function(){
s.innerHTML=story.innerHTML.substring(0,i);
i++;
if(s.innerHTML==story.innerHTML){
clearInterval(timer);
}
},200);
}
</script>
</head>
<body>
<p id="word" style="display:none;">从前有座山,山里有座庙,庙里的和尚讲故事,讲的啥故事;从前有座山。。。</p>
<p id="show"></p>
</body>
</html>
当逐字显示的内容与id=word内的内容相同时,则清除掉定时器。