這個示例實現一個位於頁面右上方的小提示框:紅底白字、圓角膠囊造型,觸發後會先放大並向上滑動,然後透明度逐級遞減直到完全消失。整個過程靠 jQuery 的 animate() 串聯完成。
function tishi() {
$("#tishi").attr("style", "border: 1px solid #000;position: absolute; z-index: 10; width:200px; height: 30px;color:white;background-color:Red;border-radius:25px;-moz-border-radius:25px; text-align:center;left:70%; top:10%; display: none");
$("#tishi").show().animate({ width: '300px', height: '37px', top: '-=10px', opacity: '0.8' }, "slow");
$("#tishi").show().animate({ top: '-=10px', opacity: '0.6' }, "slow");
$("#tishi").show().animate({ top: '-=10px', opacity: '0.4' }, "slow");
$("#tishi").show().animate({ top: '-=10px', opacity: '0.2' }, "slow");
$("#tishi").show().animate({ top: '-=10px', opacity: '0.0' }, "slow");
}
<div id="tishi" style="border: 1px solid #000; position: absolute; z-index: 10; width:200px; height: 30px;color:white; background-color:Red;border-radius:25px; -moz-border-radius:25px; /* 兼容舊版 Firefox */ text-align:center;left:70%; top: 10%; display: none">請完善信息</div>
關鍵在於把動畫拆成若干段。第一段同時改動寬高和 top,讓元素"變大並上移";後續幾段只改 top 和 opacity,通過 -=10px 這種相對值寫法實現連續位移,配合透明度從 0.8 一路降到 0,視覺上就形成了緩慢上浮、漸漸淡出的效果。
animate() 的動畫是排隊執行的,所以不必用回調嵌套,直接順序書寫即可。如果希望提示框停留一會兒再消失,可以在第一段的參數裡加上 delay 選項,或者在兩段之間插入 setTimeout。
需要注意的是,這裡用 attr("style", ...) 直接覆寫整個行內樣式,簡單但會覆蓋掉原有樣式。在正式項目中更推薦用 addClass/removeClass 配合 CSS 類來控制外觀,讓結構與樣式分離。
以上就是這個滑動提示效果的完整實現,對學習 jQuery 動畫與 DOM 操作的朋友可以作為入門參考。