准备自己写一个博客,就先做了一个自动打字的页面demo,见到过用纯css做的,但是灵活性不强,只能一个个打字打完就完了,而用js的话可以来来回回反复地打字,效果更好。
放一张效果图,演示网址:https://codepen.io/yinyoupoet/pen/RZQzVN?editors=1010
思路其实很简单,用setInterval()控制一个循环,每隔一段时间显示出一个字,然后对其显示的顺序等进行控制即可。
代码如下:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>autoType</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="first-page">
<span id="first-default">This is<p id="first-words"></p></span>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript" src="js/blog.js"></script>
</body>
</html>
css
*{
margin: 0;
padding: 0;
}
html,body{
background-color: #fff;
width: 100%;
height: 100%;
}
.first-page{
height: 100%;
width: 100%;
background-color: #0c0c0c;
}
#first-default{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
color: #fff;
font-size: 3em;
}
#first-words{
display: inline-block;
border-right: 0.08em solid #ccc;
position: relative;
top: 0;
left: 0;
}
js
$(document).ready(function(){
initAutoType();
});
var initAutoType = function(){
var types = ["a Blog.","Not Just a Blog.","YinyouPoet's Blog."];
var words = $("#first-words");
var stopType = false; //用于停止自动打字的
var index = 0;
var tempWords = "";
var isNext = false;
var time = 200;
var startType = setInterval(function(){
if(stopType){
//如果需要停止打字
clearInterval(startType);
}
if(tempWords.length === 0){
//如果删完了,就开始
if(isNext){
index++;
index = index%3;
isNext = false;
}
tempWords = types[index].substring(0,tempWords.length+1);
}else if(tempWords.length === types[index].length && isNext === false){
//如果已经到头了,就要删去
// tempWords = tempWords.substring(0,tempWords.length-1);
isNext = true;
time = 5000;
}else{
//如果既没删完也没显示完
if(isNext){
//如果是在减少
tempWords = tempWords.substring(0,tempWords.length-1);
time = 150;
}
else{
//如果在增多
time = 200;
tempWords = types[index].substring(0,tempWords.length+1);
}
}
words.html(" "+tempWords);
},time);
};