做過「滑鼠移到某個欄位,浮出一層提示」這種效果的人都知道,最惱人的不是做出浮層,而是兩個細節:滑過瞬間就發 Ajax 會把伺服器打爆,以及滑鼠從觸發點移到浮層上的途中浮層就消失了。這篇記錄了動態與非動態標籤兩套解法。
表格中的 a 標籤是 Ajax 回來後才產生的,滑鼠移入時要延遲 0.5 秒才載入資料,移出 0.5 秒後才隱藏浮層。
var outTimer; // 移出的計時器
var upTimer; // 移入的計時器
var sqDiv = $("#tm");
var test = ""; // 標識:滑鼠在浮層上時浮層不消失
var dd = ""; // 記錄當前劃過欄位傳的值
function test1(){
$("#tm").empty(); // 先清空
$.ajax({
type: "post",
url: "<%=path%>/webmodule/constructionDecision/BaseCD/getCommunityInfo.do?stCode=" + dd,
dataType: "json",
async: false,
success: function(data){
var td = "";
for (var i = 0; i < data.length; i++){
td += "<a id='" + data[i].gridNumber + "'>" + data[i].name + "</a>";
}
$("#tm").append(td);
}
});
$("#tm").show();
}
function test2(){ // 隱藏浮層
if (test == "") { $("#tm").hide(); }
}
$("#cityTable a").die().live('mouseover mouseout', function(event) {
if (event.type == 'mouseover'){
clearTimeout(outTimer); // 先清掉移出的計時器
dd = $(this).attr("id");
upTimer = setTimeout(test1, 500); // 0.5 秒後才真的載入
}
if (event.type == 'mouseout'){
sqDiv.hover(
function(){ test = "on"; }, // 滑鼠在浮層上
function(){ test = ""; test2(); }
);
clearTimeout(upTimer);
outTimer = setTimeout(test2, 500);
}
});
既然延遲 hover 是通用需求,不如包成一個 hoverDelay,讓移入與移出的延遲時間、回呼都能自訂。
$.fn.hoverDelay = function(options) {
var defaults = {
hoverDuring: 200,
outDuring : 200,
hoverEvent : function(){ $.noop(); },
outEvent : function(){ $.noop(); }
};
var sets = $.extend(defaults, options || {});
var hoverTimer, outTimer;
return $(this).each(function(){
$(this).hover(function(){
clearTimeout(outTimer);
hoverTimer = setTimeout(sets.hoverEvent, sets.hoverDuring);
}, function(){
clearTimeout(hoverTimer);
outTimer = setTimeout(sets.outEvent, sets.outDuring);
});
});
}
接著用它做出「移到欄位顯示浮層、浮層還能繼續互動」的效果,並自動處理浮層超出畫面右緣的位置問題:
$("#sosoweb").each(function(){
var test = ""; // 空 = 可隱藏;"on" = 滑鼠在浮層上
var that = $(this);
var div = $("#tm");
div.css("position", "absolute");
that.hoverDelay({
outDuring: 1000,
hoverEvent: function(){
div.css("display", "block");
var p = that.position();
var x = p.left + that.width(); // 浮層的 left
var docWidth = $(document).width(); // 網頁寬度
if (x > docWidth - div.width() - 20) { // 超出右緣就翻到左邊
x = p.left - div.width();
}
div.css("left", x);
div.css("top", p.top);
},
outEvent: function(){
$("#tm").hoverDelay({
outDuring: 1000,
hoverEvent: function(){ test = "on"; $("#tm").show(); },
outEvent : function(){ test = ""; $("#tm").hide(); }
});
if (test == "") { $("#tm").hide(); }
}
});
});
第一,範例中的 Ajax 用了 async:false(同步請求),這會凍結整個瀏覽器 UI 直到回應回來,是很糟的體驗;既然已經有延遲機制,改成非同步並在回呼裡處理即可。
第二,.die().live() 這組 API 在新版 jQuery 已移除,請改用 $(document).on('mouseover mouseout', '#cityTable a', handler) 的事件委派寫法,效果相同且更直觀。
第三,用一個全域字串 test 當旗標在多個元件間傳遞狀態,元件一多就會互相干擾。較好的做法是把狀態存進元素的 data(),或乾脆用 mouseleave 判斷包含浮層的外層容器,從根本上省掉這個旗標。