Toggle(切換)是網頁互動裡最常見的需求之一:點一下標題,內容平滑展開;再點一下,內容收攏收起。本文用原生 JavaScript 手寫一個可配置的 DIV 伸縮組件,並把實作過程中容易踩到的細節整理出來。
伸縮的本質是「用定時器反覆修改高度」。我們封裝一個 ToggleDiv 配置對象,用來描述被伸縮的元素、出發與終止高度、每次變化的步長等參數;再由 StartToggle 負責開啟或關閉的動畫迴圈;最後對外暴露一個 DoToggle 方法,讓 HTML 只要傳入兩個 id 就能完成初始化。
<script type="text/javascript" language="javascript">
function $(obj) { return document.getElementById(obj); }
function ToggleDiv() {
this.ToggleId = 'silder'; // 被伸縮的物件 ID
this.ParentId = 'container'; // 被伸縮物件的父層 ID
this.minHeight = 1; // 最小高度
this.maxHeight = 200; // 最大高度
this.speed = 1; // 伸縮速度
this.offset = 0.15; // 加速度(偏移量)
this.load = function() {
if ($(this.ToggleId).style.display == 'none') { // 目前隱藏 → 展開
StartToggle('open', this.ToggleId, this.ParentId,
this.minHeight, this.maxHeight, this.speed, this.offset);
} else { // 目前展開 → 收起
StartToggle('close', this.ToggleId, this.ParentId,
this.minHeight, this.maxHeight, this.speed, this.offset);
}
};
}
function StartToggle(method, toggleid, parentid, minheight, maxheight, speed, offset) {
if (typeof(method) != 'string' || method.toLowerCase() == '') { method = 'open'; }
if (method.toLowerCase() == 'open') {
var addspeed = speed + offset;
var openfun = function() {
var originheight = $(toggleid).offsetHeight == 0 ? 1 : $(toggleid).offsetHeight;
var newheight = originheight + addspeed;
addspeed = addspeed + offset;
if (parseInt(newheight) < parseInt(maxheight)) {
$(toggleid).style.height = newheight + 'px';
$(toggleid).style.display = 'block';
} else if (parseInt(newheight) >= parseInt(maxheight)) {
$(toggleid).style.height = maxheight + 'px';
$(toggleid).style.display = 'block';
$(parentid).innerHTML = '收縮';
window.clearInterval(addtimer);
}
};
var addtimer = window.setInterval(openfun, 100);
} else if (method.toLowerCase() == 'close') {
var addspeed = speed + offset;
var reducefunction = function() {
var originheight = $(toggleid).offsetHeight;
var newheight = originheight - addspeed;
addspeed = addspeed + offset;
if (parseInt(newheight) > parseInt(minheight)) {
$(toggleid).style.height = newheight + 'px';
$(toggleid).style.display = 'block';
} else {
$(toggleid).style.display = 'none';
$(toggleid).style.height = '1px';
$(parentid).innerHTML = '展開';
window.clearInterval(reducetimer);
}
};
var reducetimer = window.setInterval(reducefunction, 100);
}
}
function DoToggle(obj1, obj2) {
var tog = new ToggleDiv();
tog.ToggleId = obj1;
tog.ParentId = obj2;
tog.minHeight = 5;
tog.maxHeight = 110;
tog.speed = 10;
tog.offset = 3;
tog.load();
}
</script>
<div style="border:1px dashed blue;width:200px;">
<h2 id="container"
onclick="javascript:DoToggle('silder', this.id);"
onmouseover="this.style.cursor='pointer';">展開</h2>
<div id="silder" style="display:none">
伸縮效果<br />伸縮效果<br />伸縮效果<br />
伸縮效果<br />伸縮效果<br />伸縮效果<br />
</div>
</div>
點擊 h2 時把自身的 id 當作「父層」傳進去,於是文字就能在「展開/收縮」之間同步切換。
當元素設為 style.display='none' 時,讀取 offsetHeight 會得到 0;而設為 style.visibility='hidden' 時,元素仍佔據版面,讀到的會是它載入時的真實高度(例如 108)。這直接決定了展開動畫的起點怎麼算。
style.height 的值必須寫成 "108px" 而不是 "108";但 offsetHeight 回傳的是純數字 108。兩者混用是新手最常犯的錯誤。
以 setTimeout 為例:
setTimeout(function, interval, args)。第一個參數是函數或匿名函數,第二個是延遲毫秒數,第三個之後是要傳給該函數的參數。setTimeout(function(){alert('1');}, 1000)setTimeout(GetStr, 1000, 'McJeremy')setTimeout(object, function, interval)。第一個參數是物件,第二個是物件上的方法名,第三個是時間間隔。
function a() {
setTimeout(function(){ alert('1'); }, 0);
alert('2');
}
答案是先 2 再 1,而不是 1、2。原因是 JavaScript 的執行同樣有呼叫堆疊:setTimeout 的 callback 會被丟進任務佇列排隊,必須等目前這段同步程式碼跑完(包括 alert('2'))才有機會執行,即使延遲時間寫成 0 也一樣。
原始範例中難免有些冗餘程式碼,但重點是把「定時改高度」這條思路掌握住,之後要改成 CSS3 transition 版本或加上緩動函式都很容易。