這個提示框有兩個動作:點擊按鈕時從上方滑下淡入,停留幾秒後自動收起。全靠 animate 改變 top 值搭配回呼函數串接。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>jquery div提示框漸隱彈出與隱藏</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
*{margin:0;padding:0;font-size:12px;}
input{width:120px;height:30px;cursor:pointer;}
#note{position:absolute;width:400px;padding:20px;background:#eee;
border:1px solid #ccc;left:40%;z-index:9999;display:none;}
</style>
<script>
$(function(){
$('input').click(function(){
if(!$('#note').is(':visible')){
$('#note').css({display:'block', top:'-100px'})
.animate({top: '+100'}, 500, function(){
setTimeout(out, 3000);
});
}
});
});
function out(){
$('#note').animate({top:'0'}, 500, function(){
$(this).css({display:'none', top:'-100px'});
});
}
</script>
</head>
<body>
<div id="note"><a href="https://www.poluoluo.com" target="_blank"></a></div>
<input type="button" value="點我,30s後消失" />
</body>
</html>
一開始提示框是 display:none。點擊後先把它設為 display:block 並把 top 拉到 -100px(也就是畫面上方看不見的位置),接著 animate({top:'+100'}) 讓它用 500ms 滑進到 top:0 附近;動畫完成後掛一個 setTimeout(out, 3000),三秒後呼叫 out 收掉。
is(':visible') 的判斷可以避免連續點擊時動畫互相打架。若沒有這個檢查,第二次點擊會在第一次動畫還沒結束時重設 top,看起來就會跳動。
按鈕文字寫「30s 後消失」,但程式裡計時器是 3000 毫秒(3 秒)。這類文案與參數不同步是很常見的小疏漏,上線前值得對一遍。
目前的多重計時器沒有清除機制,連續觸發時可能疊出好幾個 setTimeout。實務上建議把 timeout handle 存起來,重新觸發前先 clearTimeout;或者改用 .stop(true) 搭配 queue 控制,讓動畫與計時都只有一份在跑。