Javascrpit特效之打字機效果
今天來看看怎麼實現炫酷的打字機效果。即把一段話一個字一個字的顯示出來。
效果圖:
實現思路:
首先規定好顯示字數的速度即settimeout執行間隔用來控制每個字之間輸出速度。再把判斷段落的總字數,循環段落總字數來實現一個字一個字的輸出。
js代碼:
var theNewsNum;
var theAddNum;
var totalNum;
var CurrentPosion=0;
var theCurrentNews;
var theCurrentLength;
var theNewsText;
var theTargetLink;
var theCharacterTimeout;
var theNewsTimeout;
var theBrowserVersion;
var theWidgetOne;
var theWidgetTwo;
var theSpaceFiller;
var theLeadString;
var theNewsState;
function startTicker(){
// ------ 設置初始數值
theCharacterTimeout = 50;//字符間隔時間
theNewsTimeout = 2000;//新聞間隔時間
theWidgetOne = "_";//新聞前面下標符1
theWidgetTwo = "-";//新聞前面下標符
theNewsState = 1;
theNewsNum = document.getElementById("incoming").children.AllNews.children.length;//新聞總條數
theAddNum = document.getElementById("incoming").children.AddNews.children.length;//補充條數
totalNum =theNewsNum+theAddNum;
theCurrentNews = 0;
theCurrentLength = 0;
theLeadString = " ";
theSpaceFiller = " ";
runTheTicker();
}
// --- 基礎函數
function runTheTicker(){
if(theNewsState == 1){
if(CurrentPosion<theNewsNum){
setupNextNews();
}
else{
setupAddNews();
}
CurrentPosion++;
if(CurrentPosion>=totalNum||CurrentPosion>=1){
CurrentPosion=0;//最多條數不超過num_gun條
}
}
if(theCurrentLength != theNewsText.length){
drawNews();
}
else{
closeOutNews();
}
}
// --- 跳轉下一條新聞
function setupNextNews(){
theNewsState = 0;
theCurrentNews = theCurrentNews % theNewsNum;
theNewsText = document.getElementById("AllNews").children[theCurrentNews].children.Summary.innerText;
theTargetLink = document.getElementById("AllNews").children[theCurrentNews].children.Summary.children[0].href;
theCurrentLength = 0;
document.all.hottext.href = theTargetLink;
theCurrentNews++;
}
function setupAddNews() {
theNewsState = 0;
theCurrentNews = theCurrentNews % theAddNum;
theNewsText = document.getElementById("AllNews").children[theCurrentNews].children.Summary.innerText;
theTargetLink = document.getElementById("AllNews").children[theCurrentNews].children.Summary.children[0].href;
theCurrentLength = 0;
document.all.hottext.href = theTargetLink;
theCurrentNews++;
}
// --- 滾動新聞
function drawNews(){
var myWidget;
if((theCurrentLength % 2) == 1){
myWidget = theWidgetOne;
}
else{
myWidget = theWidgetTwo;
}
document.all.hottext.innerHTML = theLeadString + theNewsText.substring(0,theCurrentLength) + myWidget + theSpaceFiller;
theCurrentLength++;
setTimeout("runTheTicker()", theCharacterTimeout);
}
// --- 結束新聞循環
function closeOutNews(){
document.all.hottext.innerHTML = theLeadString + theNewsText + theSpaceFiller;
theNewsState = 1;
setTimeout("runTheTicker()", theNewsTimeout);
}
window.οnlοad=startTicker;