上一篇談的是動態建立節點與刪除節點,這一篇來看如何用 setTimeout 與 setInterval 做出簡單的動畫效果。
兩者的語法都是 window.setTimeout(fn, delay) 與 window.setInterval(fn, delay)。
fn 可以是一個函數名稱,也可以是一段可執行的字串。但要特別小心:如果 fn 是字串、而且裡面又帶了物件參數,例如 window.setInterval("myFunction(obj)", 1000),很可能會拋出例外。這種情況我建議一律改成下面這種寫法:
window.setInterval(function () {
myFunction(obj);
}, 1000);
另一種常見場景是在「類別」裡面要呼叫 this.myFunction(obj),這時候可以先用一個區域變數把 this 抓下來:
function jsclass() {};
jsclass.prototype.init = function (obj) {
var self = this; // 先把 this 的參考存起來
window.setInterval(function (obj) {
self.myFunction(obj);
}, 1000);
};
jsclass.prototype.myFunction = function (obj) {
// TODO
};
這兩個是挂在 window 層級的全域方法,不屬於 DOM 元素的成員。差別很單純:setInterval 會重複執行,setTimeout 只執行一次。因為它們本來就掛在 window 上,前面不寫 window 也完全可以用。
兩者都會回傳一個數字型的 timerId,之後可以交給 clearInterval / clearTimeout 來取消。做過桌面開發的人不妨這樣類比:setInterval 就像建立一條執行緒,timerId 是它的 thread id,clearInterval 則是把它銷毀。這樣想會比較好理解。
(就個人習慣而言,實際開發中我更傾向用 setTimeout 自行遞迴。)
一秒後跳出一個 alert:
<script>
window.setTimeout(function () {
alert("timeout example after 1 second");
}, 1000)
</script>
每一秒動態建立一個新的 DIV:
<script>
function intervalExample() {
var div = document.createElement("div");
div.innerHTML = "tutorial of DHTML and javascript programming";
document.body.appendChild(div);
}
window.setInterval(intervalExample, 1000);
</script>
實際專案裡,setTimeout 有個比較另類但很實用的玩法——它的效果有點像 VB 的 DoEvents,或 .NET 桌面程式裡的 Application.DoEvents(),也就是「讓出控制權」的異步處理。
DHTML 沒有多執行緒,所以這個技巧在很多時候是為了避免畫面看起來像當機,或是讓後續程式碼依邏輯繼續跑下去而不互相阻塞。
舉例來說,下面這段沒有加 setTimeout,執行後錨點會立刻跳到 hash2:
<script> window.location.hash = "hash1"; window.location.hash = "hash2"; </script>
而這一段加了 setTimeout,錨點會在 3 秒後指向 hash1,再過 3 秒才指向 hash2:
<script>
var doEventsDelay = 0;
function DoEvents(fn) {
window.setTimeout(fn, doEventsDelay);
doEventsDelay += 3000;
}
DoEvents(function () {
window.location.hash = "hash1";
doEventsDelay -= 3000;
});
DoEvents(function () {
window.location.hash = "hash2";
doEventsDelay -= 3000;
});
</script>
有了觀念,來做個實用一點的例子:滑過選單時,用動態產生的 tip 容器做出一段滑出動畫。
一、這裡只講 setTimeout 的做法,setInterval 的版本請參考 demo 程式碼。另外要提醒的是,本例還留著一個關於座標的問題沒解決(把 sliderShow 放進 table 裡就可能出狀況),這個我留待以後再談。
二、整體思路是:先取得目標元素相對於文件的 X、Y 座標,再依據 tip 容器的位置做位移,一點一點把動畫跑出來。關於各個座標屬性的意義,見下圖:
整個動畫的執行流程則如下圖所示:
三、範例程式碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Slider Show Demo</title>
<style type="text/css" media="all" title="Default">
* { font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; margin:0; }
body { font-size:10pt; text-align:center; }
.sliderShowBox {
border:1px solid #333;
visibility:hidden;
position:absolute;
background-color:#eee;
overflow:hidden;
width:250px;
text-align:left;
}
.sliderShowContent { padding:5px; }
</style>
</head>
<body>
<h1>Slider Show Demo</h1>
<hr/>
<!-- 這裡掛上 sliderShow 的呼叫與腳本 -->
</body>
</html>
最後留個功課給你:上面這段 JavaScript 裡將近一半都是重複的勞動,很多地方都可以抽成函數來精簡。這裡我就不代勞了,把這份優化工作留給大家練習,順便把程式碼的冗餘去掉。