右下角浮動廣告是舊時代網站的常見物:平時只露出小小一條標題列,經過一段時間自動展開一次,使用者也可以自行開合。以下示範以 jQuery 的 animate 與 toggle 實作,並加上定時控制。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>測試</title>
<style type="text/css">
.divCss {
bottom: 0;
display: block;
height: 25px;
overflow: hidden;
padding: 0;
position: fixed;
right: 20px;
}
.contentCss { background: #666; height: 200px; width: 200px; }
.titleCss { width: 200px; height: 25px; line-height: 25px;
text-align: right; margin: 0px; background: #999999; }
#close { cursor: pointer; }
</style>
<script language="javascript" type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
var titHeight = $("#ditTitle").height(); // 標題層高度
var conHeight = $("#divContent").height(); // 內容層高度
$("#close").toggle(function(){
$("#close").text("關閉");
$("#msgDiv").animate({ height: titHeight + conHeight }, 1000);
}, function(){
$("#close").text("打開");
$("#msgDiv").animate({ height: titHeight }, 1000);
});
// 定時控制:第 4 秒展開,第 8 秒收合
var myTimer, i = 8;
function starFun() {
if (i == 4) $("#close").click();
if (i == 0) {
window.clearTimeout(myTimer);
if ($("#close").text() != "打開") $("#close").click();
}
myTimer = window.setTimeout(starFun, 1000);
i = i - 1;
}
starFun();
});
</script>
</head>
<body>
<div style="height: 1000px; background: #ccc;">測試 Div</div>
<div id="msgDiv" class="divCss">
<div id="ditTitle" class="titleCss"><span id="close">打開</span></div>
<div id="divContent" class="contentCss">這裡放測試內容</div>
</div>
<div style="height: 1000px; background: #C0C0C0;">測試 Div</div>
</body>
</html>
收合狀態靠 overflow: hidden 加固定高度。容器高度固定為 25px(只夠放標題列),內容超出部分被裁掉;展開時把 height 動畫到「標題加內容」的高度,內容自然露出來。
定位靠 position: fixed 加 bottom / right。這樣 regardless 頁面捲動,廣告都黏在視窗右下角。上方與下方各放一個 1000px 高的佔位 div,就是為了製造可捲動的空間來驗證這件事。
開合狀態用 toggle 維護。第一次點擊展開、第二次點擊收合,同時把文字在「打開/關閉」之間切換,讓使用者知道現在點下去會發生什麼。
定時腳本用遞減計數器。i 從 8 數到 0,每秒觸發一次;i==4 時點擊展開,i==0 時清除計時器並確保收合。用計數器而非絕對時間,是為了避免 setTimeout 單點觸發難以取消的問題。
經測試,IE6 無法正常運作這個範例。考量到這個手法本質上是打斷使用者閱讀的插入式廣告,多數情境下並不建議真正上線;若必須使用,請至少做到三件事:提供明確的關閉按鈕、不要自動反覆彈出、并且在使用者關閉後以 cookie 或 localStorage 記錄,避免每次換頁就再來一次。
另外,若需要支援 IE6,position: fixed 必須額外處理(例如以 position: absolute 搭配捲軸位置補償),這也是這個範例在舊 IE 上失效的主因之一。