表單送出成功、資料刪除完成、密碼已更新——這些時候都需要給使用者一個回饋。與其跳出 alert() 打斷操作,不如做一個浮動提示層:出現在視窗上方中央,幾秒後自己淡出。以下是一個可直接複用的函式。
/**
* 浮動 DIV 定時顯示提示訊息,如操作成功、失敗等
*
* @param string tips 提示的內容
* @param int height 顯示位置距瀏覽器頂部的高度
* @param int time 顯示時間(秒),須 > 0
*
* @sample <a href="javascript:void(0);" onclick="showTips('操作成功', 100, 3);">點擊</a>
* @sample 上式代表點擊後顯示「操作成功」3 秒鐘,距頂部 100px
*/
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 ) );
}
<a href="javascript:void(0);" onclick="showTips('操作成功', 100, 3);">點擊</a>
$(element).width(),或用 position:fixed; left:50%; transform:translateX(-50%) 讓瀏覽器自己算。$('div.tipsClass').remove()。tipsSuccess / tipsError),讓使用者不必讀字就知道結果。整體只有三十來行,卻涵蓋了動態建立元素、設定樣式、計時移除三個常用技巧,很適合當作自己的工具函式庫起點。