操作成功、資料已儲存這類短暫回饋,用 alert 會打斷使用者的動作,用紅字塞在頁面裡又容易位置錯亂。比較好的做法是浮在畫面上顯示幾秒,然後自己淡出。
/**
* 浮動 DIV 定時顯示提示訊息,如操作成功、失敗等
* @param string tips (提示的內容)
* @param int height (距離瀏覽器頂部的高度)
* @param int time (顯示時間,單位秒,需 > 0)
*
* @sample <a href="javascript:void(0);" onclick="showTips('操作成功', 100, 3);">點擊</a>
* @sample 上式表示點擊後在距頂 100px 處顯示「操作成功」3 秒鐘
* @copyright ZhouHr 2010-08-27
*/
function showTips( tips, height, time ){
var windowWidth = document.documentElement.clientWidth;
var tipsDiv = '<div class="tipsClass">' + tips + '</div>';
$('body').append(tipsDiv);
$('div.tipsClass').css({
'top': height + 'px',
'left': ( windowWidth / 2 ) - ( tips.length * 13 / 2 ) + 'px',
'position': 'absolute',
'padding': '3px 5px',
'background': '#8FBC8F',
'font-size': 12 + 'px',
'margin': '0 auto',
'text-align': 'center',
'width': 'auto',
'color': '#fff',
'opacity': '0.8'
}).show();
setTimeout(function(){ $('div.tipsClass').fadeOut(); }, ( time * 1000 ));
}
關鍵那一行是 (windowWidth / 2) - (tips.length * 13 / 2):先取視窗半寬當中心,再減掉「文字寬度的一半」。文字寬度則用「字數 × 每字約 13px」估算。
這個估算很粗糙——中文字、英文字、標點的實際寬度差很多,字型大小一變就失準。真正可靠的做法有兩個:
// 做法一:先讓它顯示出來,量到實際寬度再定位
$('div.tipsClass').css({ top: height + 'px', position: 'absolute' }).show();
var w = $('div.tipsClass').outerWidth();
$('div.tipsClass').css('left', (windowWidth - w) / 2 + 'px');
// 做法二:交給 CSS
// .tipsClass { position: fixed; left: 0; right: 0; margin: 0 auto; width: 12em; }
不要用 class 選單元素。連續觸發兩次時,頁面上會同時存在兩個 .tipsClass,setTimeout 到來時會把兩者一起淡出,第一個提示因而提前消失。改成用 id,或在建立新的之前先把舊的 remove 掉。
fadeOut 之後要 remove。fadeOut 只是 display: none,節點仍留在 DOM 裡。長時間使用的頁面會一層層累積。改成 fadeOut(function(){ $(this).remove(); }) 才是完整收尾。
position 建議用 fixed。範例用 absolute,因此捲動頁面時提示會跟著跑掉。若希望它固定在視窗上,改用 fixed 並把 top 的基準從文件改為視窗即可(舊 IE 需另行處理)。
直接內插 HTML 有 XSS 風險。tips 參數被原封不動塞進 html(),若內容來自使用者輸入,就等於開了一個後門。請視情境改用 .text(tips),或先經過轉義處理。
function showTips(tips, height, time) {
height = height || 100;
time = time || 3;
$('#tipsClass').remove(); // 先清掉舊的
var $t = $('<div></div>')
.attr('id', 'tipsClass')
.addClass('tipsClass')
.text(tips) // 用 text 避免 XSS
.css({ top: height + 'px', position: 'fixed', opacity: 0.8 })
.appendTo('body');
var w = $t.outerWidth();
$t.css('left', (($(window).width() - w) / 2) + 'px');
setTimeout(function(){
$t.fadeOut(300, function(){ $(this).remove(); });
}, time * 1000);
}