客服浮窗、回到頂部按鈕、線上諮詢入口——這些都需要「不管頁面捲到哪裡,都固定停在螢幕某個位置」的效果。以下是一個功能完整的 jQuery 外掛 floatdiv,支援九種預設位置與自訂座標,並處理了舊版 IE 的相容問題。
可讓指定的層浮動在網頁上的任何位置,捲動時保持在原位不會跑掉,也不會產生閃動。這個版本演進過程如下:
1. 無參數呼叫(預設浮動在右下角)
$("#id").floatdiv();
2. 內建固定位置
$("#id").floatdiv("rightbottom"); // 右下角
$("#id").floatdiv("leftbottom"); // 左下角
$("#id").floatdiv("lefttop"); // 左上角
$("#id").floatdiv("righttop"); // 右上角
$("#id").floatdiv("middle"); // 正中央
// 另外新增的四個位置
$("#id").floatdiv("middletop"); // 居中置頂
$("#id").floatdiv("middlebottom"); // 居中置底
$("#id").floatdiv("leftmiddle"); // 左側居中
$("#id").floatdiv("rightmiddle"); // 右側居中
3. 自訂位置
$("#id").floatdiv({ left: "10px", top: "10px" });
// 浮動層會定位在 left 10px、top 10px 處
jQuery.fn.floatdiv = function (location) {
// 判斷是否為 IE6
var isIE6 = false;
var Sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : 0;
if (Sys.ie && Sys.ie == "6.0") { isIE6 = true; }
var windowWidth, windowHeight; // 視窗寬高
if (self.innerHeight) {
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) {
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
return this.each(function () {
var loc; // 層的定位設定
var wrap = $("<div></div>");
var top = -1;
if (location == undefined || location.constructor == String) {
switch (location) {
case ("rightbottom"):
loc = { right: "0px", bottom: "0px" }; break;
case ("leftbottom"):
loc = { left: "0px", bottom: "0px" }; break;
case ("lefttop"):
loc = { left: "0px", top: "0px" }; top = 0; break;
case ("righttop"):
loc = { right: "0px", top: "0px" }; top = 0; break;
case ("middletop"):
loc = { left: windowWidth / 2 - $(this).width() / 2 + "px", top: "0px" };
top = 0; break;
case ("middlebottom"):
loc = { left: windowWidth / 2 - $(this).width() / 2 + "px", bottom: "0px" };
break;
case ("leftmiddle"):
loc = { left: "0px", top: windowHeight / 2 - $(this).height() / 2 + "px" };
top = windowHeight / 2 - $(this).height() / 2; break;
case ("rightmiddle"):
loc = { right: "0px", top: windowHeight / 2 - $(this).height() / 2 + "px" };
top = windowHeight / 2 - $(this).height() / 2; break;
case ("middle"):
var l = windowWidth / 2 - $(this).width() / 2;
var t = windowHeight / 2 - $(this).height() / 2;
top = t;
loc = { left: l + "px", top: t + "px" }; break;
default:
location = "rightbottom";
loc = { right: "0px", bottom: "0px" };
break;
}
} else {
loc = location;
var str = loc.top;
// 加上 top 為空值時的判斷
if (typeof (str) != 'undefined') {
str = str.replace("px", "");
top = str;
}
}
/* IE6 的 CSS hack */
if (isIE6) {
if (top >= 0) {
wrap = $('<div style="top:expression(documentElement.scrollTop+' + top + ');"></div>');
} else {
wrap = $('<div style="top:expression(documentElement.scrollTop+documentElement.clientHeight-this.offsetHeight);"></div>');
}
}
$("body").append(wrap);
wrap.css(loc).css({ position: "fixed", z_index: "999" });
if (isIE6) {
wrap.css("position", "absolute");
// 若不加上下面這段,IE6 使用 expression 時會出現跳動
$("body").css("background-attachment", "fixed")
.css("background-image", "url(n1othing.txt)");
}
$(this).appendTo(wrap); // 把要固定的層放進固定層裡
});
};
整個外掛的核心手法是「包一層」:不直接把目標元素設為 fixed,而是先建一個空的 div 作為定位容器(wrap),設好它的位置與 position: fixed,再把目標元素 append 進去。這樣做的好處是定位邏輯與內容完全分離,同一個頁面可以有多個浮動層各自獨立定位。
至於 IE6 不支援 position: fixed 這個歷史問題,這裡用 CSS expression 動態計算 top 來模擬。那段把 body 的 background-image 指向一個不存在的檔案的 hack,是為了消除 expression 造成的閃動——屬於那個年代的經典技巧。
這個外掛寫於 2009 年,以現在的標準來看有幾點值得調整。IE6 早已不在支援清單中,整段 isIE6 分支可以移除,position: fixed 現在所有主流瀏覽器都支援。另外 z_index 是無效的 CSS 屬性名稱,正確應為 zIndex;而 location.constructor == String 這種型別判斷可以改成 typeof location === "string",更直覺。
精簡之後,同樣的功能只需要幾行:
jQuery.fn.floatdiv = function (pos) {
var map = {
rightbottom: { right: 0, bottom: 0 },
leftbottom: { left: 0, bottom: 0 },
lefttop: { left: 0, top: 0 },
righttop: { right: 0, top: 0 },
middle: {}
};
return this.css($.extend({ position: "fixed", zIndex: 999 }, map[pos] || pos || map.rightbottom));
};
$("#id").floatdiv("lefttop");
若需要居中,用 CSS 的 left: 50%; transform: translateX(-50%) 就能取代程式中的寬高計算,不必再手動讀 windowWidth。