|
|
|
|
|
|
本文介紹比較常見的文本打字效果,該效果使用JavaScript來實現。


完整HTML代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript文本打字效果</title>
<style type="text/css">
body {
background:#333333;
color: #27f7f7;
.container{margin: 2.5em;
padding: 15px;
border-radius: 8px;
}
.console {
height: 100px;
padding: 1.875em;
background: #191919;
box-shadow: 0 0 15px 2px #7Cbdbd inset;
border: 2px solid #3acaec;
border-radius: 5px;
}
p {
font-family: "Orbitron",sans-serif;
font-size: 100%;
font-weight: normal;
letter-spacing: .1rem;
line-height: 200%;
}
.char {
color: #fff;
transition: color ease-out .3s,text-shadow ease-out .3s;
text-shadow: 0 0 4rem #fff;
}
.char.fade-in {
color: #0cf;
transition: color ease-out .3s,text-shadow ease-out .3s;
text-shadow: 0 0 1rem #0cf;
}
</style>
</head>
<body>
<div class="container">
<div class="console">
<code><p>演示:JavaScript文本打字效果 ———— webkaka.com</p></code> </div>
</div>
<script type="text/javascript">
var title = document.querySelector("p");
var CHAR_TIME = 30;
var text = void 0,index = void 0;
function requestCharAnimation(char, value) {
setTimeout(function () {
char.textContent = value;
char.classList.add("fade-in");
}, CHAR_TIME);
}
function addChar() {
var char = document.createElement("span");
char.classList.add("char");
char.textContent = "▌";
title.appendChild(char);
requestCharAnimation(char, text.substr(index++, 1));
if (index < text.length) {
requestChar();
}
}
function requestChar() {var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
setTimeout(addChar, CHAR_TIME + delay);
}
function start() {
index = 0;
text = title.textContent.trim();
title.textContent = "";
requestChar(1000);
}
start();
</script>
</body>
</html>
代碼解釋
var title = document.querySelector("p"); 是選擇標簽為p的內容,這是需要以打字效果輸出的文本。
var CHAR_TIME = 30; 是光標移動速度,即是打字速度。數值越小,速度越快。
function start() {
index = 0;
text = title.textContent.trim();
title.textContent = "";
requestChar(1000);
}
start();start();開始執行程序,start()函數里把要打字的文字賦給一個變量text,然后清空原文字title.textContent = "";,接著調用另一個函數requestChar(),該函數里使用setTimeout(),按一定頻率調用打字函數addChar() ,整個打字效果的實現方法就是這樣。
