show() 與 hide() 除了單純的顯示隱藏,還能帶入速度參數變成動畫。這個範例用兩個按鈕分別控制同一張圖片的展開與收合,時間設為 5000 毫秒以便觀察過程。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
#img1 {
width: 400px;
height: 400px;
border: solid 1px #ccc;
display: none;
}
</style>
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#Button1').click(function () {
$('#img1').show(5000); // 展開圖片
});
$('#Button2').click(function () {
$('#img1').hide(5000); // 收合圖片
});
});
</script>
</head>
<body>
<img id="img1" src="images/1.jpg" />
<input id="Button1" type="button" value="展開圖片"/>
<input id="Button2" type="button" value="收縮圖片"/>
</body>
</html>
show/hide 可接受 "slow"、"fast" 或毫秒數字三種寫法,不帶參數則是瞬間切換、沒有過渡動畫。範例裡用 5000 是刻意放慢方便教學,實務上 200 ~ 400 毫秒的節奏通常最自然。
第一,動畫期間連續點擊會堆疊效果。使用者連點數次「展開」,jQuery 會把動畫排進佇列依序播放,畫面看起來像卡住。加上 .stop(true) 可以清掉佇列,讓新的操作立即接管。
第二,show/hide 切換的是 display,不是可見性。它會佔用版面,與 visibility: hidden 或 opacity: 0 的行為不同,排版上要留意。
第三,想「一個按鈕來回切換」就用 toggle():$('#Button1').click(function(){ $('#img1').toggle(1000); });,不必自己維護狀態變數。