很多網站會在頁面頂端放一條提示訊息橫幅,載入時平滑滑下、點擊關閉鈕時再優雅收起。本文用 jQuery 的 slideDown 與 slideUp 實作這個效果,並示範如何搭配 AJAX 記錄使用者已讀狀態。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>提示層範例</title>
<style>
#screefull{display:block; border:1px solid #bddbf3; width:954px; padding:3px 5px 7px; margin:0 auto 10px; background:#fef9db; }
#mostrar{display:block; width:954px; display:none;}
#screefull a.close{ display:block; width:25px; height:20px; background:url(img/cx.gif) no-repeat 0 0; overflow:hidden; float:right; margin:16px 8px 0 0; *margin-right:5px; text-decoration:none;}
#screefull p{ display:block; text-align:center; font-family:"Microsoft Yahei"; font-size:14px; color:#000; height:28px; line-height:28px; vertical-align:middle;}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div id="warn" class="scree clearfix" style="display:none;">
<div id="screefull">
<a href="#" class="close" onclick="closewarn('close')">[x]</a>
<p><span>在<em>未通過審核的網站</em>添加廣告代碼,將不會產生傭金。<a href="#" target="_blank">我知道了</a></span></p>
</div>
</div>
<script type="text/javascript">
function closewarn(type) {
$("#warn").slideUp("slow");
if(type == 'know') {
$.post(window.location.href, {op : 'setwarn'}, function(data) {
return true;
});
}
}
window.onload = function() {
$("#warn").slideDown(2000);
}
</script>
</body>
</html>
一、滑動動畫:$("#warn").slideUp("slow") 向上收起,$("#warn").slideDown(2000) 向下展開,數值代表毫秒。
二、AJAX 提交:$.post(url, data, success) 三個參數分別是請求位址、提交參數、成功後呼叫的函式。這裡用來把「已讀」狀態回傳伺服器,避免下次再跳出相同提示。
三、window.onload:把提示層的展開邏輯放在 onload 中,可以確保頁面完全載入後才執行,不必等到 body 中觸發。
這個範例示範了如何用最少的程式碼,做出既視覺友善、又能記錄使用者狀態的提示橫幅,很適合用在站內公告或一次性引導訊息上。