要做出一個「雙擊叫出、可拖曳、再點一下自動收起」的浮動菜單,需要處理四件事:定位、展開動畫、拖曳、以及點擊空白處關閉。以下逐段拆解。
var obj;
function loadobj(o) {
obj = o;
}
用 setTimeout 每 25 毫秒長高 17px、加寬 6px,直到接近目標尺寸(約 60×174)就停止並把尺寸固定下來。
function expand() {
var h = parseInt(obj.height);
var w = parseInt(obj.width);
if (h <= 170) {
if (w < 60) { obj.style.width = w + 6; }
obj.style.height = h + 17;
x = setTimeout('expand()', 25);
} else {
obj.style.width = 60;
obj.style.height = 174;
clearTimeout(x);
}
}
滑鼠左鍵雙擊時,把菜單的左上角對齊游標位置,尺寸歸零後套用 IE 的 filters 轉場特效(transition = 25 為由中央向外擴散),再呼叫 expand() 完成展開。
var drag = 0;
var move = 0;
function Dblclick() {
if (event.button == 0) {
obj.style.visibility = "visible";
obj.style.left = window.event.x;
obj.style.top = window.event.y;
obj.style.width = 0;
obj.style.height = 0;
obj.filters.item(0).apply();
obj.filters.item(0).transition = 25;
obj.filters(0).play(0.5);
expand();
}
}
拖曳的關鍵是先算出游標與元素左上角的偏移量 l、t,移動時用「游標座標減偏移」當新座標,這樣元素才不會在抓取瞬間跳位。
function MouseMove() {
if (move == 1) {
obj.style.cursor = "move";
obj.style.left = window.event.x - l;
obj.style.top = window.event.y - t;
}
}
function MouseDown() {
if (drag) {
l = window.event.x - parseInt(obj.style.left);
t = window.event.y - parseInt(obj.style.top);
obj.style.zIndex += 1;
move = 1;
} else {
document.body.style.cursor = 'default';
obj.style.visibility = 'hidden'; // 不在拖曳狀態時,按下即收起
}
}
function MouseUp() {
move = 0;
obj.style.cursor = "hand";
}
function MouseStop() {
window.event.returnValue = false; // 取消瀏覽器原生的拖曳行為
}
document.ondblclick = Dblclick; document.onmousedown = MouseDown; document.onmousemove = MouseMove; document.ondragstart = MouseStop; document.onmouseup = MouseUp;
整份程式的骨架其實很通用:用一個絕對定位的容器 + 狀態旗標 + 定時器,就能做出各種彈出層。若要搬到今天的瀏覽器,只要把三處換掉即可:
一是事件寫法改用 addEventListener,事件座標改用 event.clientX/clientY;二是 filters 轉場改成 CSS transition 或 transform: scale();三是把 parseInt(obj.style.left) 這類字串解析,改成用 offsetLeft、offsetTop 讀取實際位置,可以避免初始值為空字串時算出 NaN。