頁面操作反饋常需「顯示幾秒後自動淡出」的 Toast 提示。jQuery 提供鏈式動畫隊列輕鬆實現。本文對比 show/delay/hide、fadeTo、fadeOut、slideUp 等方案,給出生產級封裝函數。
$('#msg').html('操作成功').show(300).delay(3000).hide(300);
show(300):300ms 淡入/滑下顯示。delay(3000):在動畫隊列中等待 3 秒。hide(300):300ms 淡出/滑上隱藏。$('#msg').html('提示').fadeTo(300, 1).delay(3000).fadeTo(300, 0, function () {
$(this).hide(); // 完全透明後隱藏,佔位消失
});
function showToast(msg, duration = 3000) {
var $el = $('#toast').html(msg);
$el.stop(true, true) // 清除舊動畫隊列,防疊加
.fadeIn(200)
.delay(duration)
.fadeOut(300, function () { $(this).css('display', ''); }); // 重置 inline display
}
showToast('保存成功');
showToast('網絡錯誤', 5000);
$('#banner').html('新版本發布,點擊更新')
.slideDown(300)
.delay(5000)
.slideUp(300);
var Toast = (function () {
var $el, timer;
function ensure() {
if (!$el) {
$el = $('')
.appendTo('body');
}
}
return function (msg, ms) {
ensure();
clearTimeout(timer);
$el.stop(true, true).html(msg).fadeIn(150);
timer = setTimeout(function () {
$el.fadeOut(200);
}, ms || 2500);
};
})();
// 使用
Toast('數據已同步');
Toast('權限不足', 4000);
#toast, #msg {
position: fixed;
left: 50%; transform: translateX(-50%);
bottom: 30px;
padding: 10px 20px;
background: rgba(0,0,0,0.8);
color: #fff;
border-radius: 4px;
font-size: 14px;
display: none; /* 初始隱藏 */
z-index: 9999;
}
function toast(msg, ms = 2500) {
var el = document.getElementById('toast');
if (!el) {
el = document.createElement('div');
el.id = 'toast';
Object.assign(el.style, {
position: 'fixed', left: '50%', bottom: '30px', transform: 'translateX(-50%)',
padding: '10px 20px', background: 'rgba(0,0,0,.8)', color: '#fff',
borderRadius: '4px', display: 'none', zIndex: 9999, transition: 'opacity .2s'
});
document.body.appendChild(el);
}
el.textContent = msg;
el.style.display = 'block';
el.style.opacity = '1';
clearTimeout(el._timer);
el._timer = setTimeout(() => {
el.style.opacity = '0';
setTimeout(() => el.style.display = 'none', 200);
}, ms);
}
fadeIn/delay/fadeOut 或封裝 Toast 單例。toast() 函數,無依賴、體積極小。核心模式:顯示 → 延遲 → 淡出 → 隱藏,善用 .stop(true,true) 防動畫疊加,單例模式避免重複創建 DOM。