作者:沒劍 2008-07-03 https://regedit.cnblogs.com
showobj:要顯示的選單 IDtimeout:延時時間,滑鼠停留/離開後延時多久才開始顯示/隱藏選單(預設 300 毫秒)speed:選單顯示速度,數字越大顯示越慢(預設 100)呼叫範例:$("#button").DMenu("#content");
/* 彈出式選單 */
jQuery.fn.DMenu = function(showobj, timeout, speed){
timeout = timeout ? timeout : 300;
speed = speed ? speed : 100;
var button = $(this); // 按鈕物件
var timer = null; // 延時計數器
var hideDiv = $("<div></div>"); // 隱藏的浮動層
var Container = $("<div id=\"Container\"></div>");
Container.hide();
hideDiv.append(Container);
var jqShowObj = $(showobj); // 選單物件
jqShowObj.hide(); // 先隱藏選單
var display = false; // 選單顯示狀態
var offset = button.offset(); // 按鈕的位置
var height = jqShowObj.height(); // 選單區高
var width = jqShowObj.width(); // 選單區寬
var btnHeight = button.height(); // 按鈕的高
var btnWidth = button.width(); // 按鈕的寬
$(document.body).prepend(hideDiv); // 定位層放到最前面
// **** 顯示選單方法開始 ****
var showMenu = function(){
if (display) { return false; } // 已顯示則退出
Container.css({
margin: "0 auto",
width: btnWidth + "px",
height: btnHeight + "px"
});
// 依按鈕位置定位隱藏層,並讓選單水平居中於按鈕
hideDiv.css({
position: "absolute",
top: offset.top + "px",
left: offset.left + (btnWidth/2) - (width/2) + "px",
height: height + "px",
width: width + "px"
}).show();
Container.css({ border: "1px solid #666666" }); // 動畫期間先加黑邊框
// 高寬慢慢增大,形成展開動畫
Container.animate({
marginTop: btnHeight + 4,
height: height + 4,
width: width + 4,
opacity: '100'
}, speed, function(){
// 動畫結束
jqShowObj.show();
Container.append(jqShowObj);
Container.css({ border: "0px" }); // 移除邊框
display = true;
jqShowObj.mouseover(function(){ clearTimeout(timer); });
jqShowObj.mouseout(function(){ hideMenu(); });
});
};
// **** 顯示選單方法結束 ****
// **** 隱藏選單方法開始 ****
var hideMenu = function(){
clearTimeout(timer);
timer = setTimeout(function(){
Container.css({ border: "1px solid #666666" });
Container.empty(); // 清空容器
// 收縮容器
Container.animate({
width: btnWidth,
height: btnHeight,
marginTop: '0',
opacity: '0'
}, speed, function(){
Container.hide();
hideDiv.hide();
display = false;
});
}, timeout);
};
// **** 隱藏選單方法結束 ****
// 綁定按鈕的滑鼠移入移出事件
button.hover(function(e){
clearTimeout(timer);
timer = setTimeout(function(){ showMenu(); }, timeout);
}, function(){
clearTimeout(timer);
if(display){
timer = setTimeout(function(){ hideMenu(); }, timeout);
}
});
};
這個外掛的展開效果不是直接 show/hide,而是:先加上 1px 深色邊框,再用 animate 把容器的 width、height、marginTop 從按鈕尺寸逐步放大到選單尺寸,動畫結束後才把真正的選單內容塞進去並移除邊框。收合時反向操作,並在動畫期間保留邊框。這樣做出來的視覺效果就有如選單是從按鈕「長出來」的一樣。
而 timeout 的延時設計(滑鼠移出後等 300 毫秒才收合)是為了避免使用者移動滑鼠的路徑短暫離開按鈕時,選單就瞬間消失——這是彈出式選單最容易失敗的地方。
註:關於 select 元素會擋住彈出選單的問題,因為與外掛本身無關,此處未做處理。把 select 放在哪個位置只是想提醒各位:使用彈出式選單時要注意這個經典的 z-index 層級問題,的解決方式可自行搜尋,或在版面配置上避開。