同一張圖片、四個按鈕,分別用 show/hide 與 fadeIn/fadeOut 控制,可以很直觀地比較兩組效果的差異。
<!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>
<title></title>
<style type="text/css">
#img1 {
width: 500px;
height: 400px;
border: solid 1px #ccc;
display: none;
}
</style>
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
$('#img1').show(5000); // 展開
});
$('#Button2').click(function () {
$('#img1').hide(5000); // 收合
});
$('#Button3').click(function () {
$('#img1').fadeIn(2000); // 淡入
});
$('#Button4').click(function () {
$('#img1').fadeOut(1000); // 淡出
});
});
</script>
</head>
<body>
<img id="img1" src="images/1.jpg" />
<input id="Button1" type="button" value="展開圖片" />
<input id="Button2" type="button" value="收縮圖片" />
<input id="Button3" type="button" value="淡入" />
<input id="Button4" type="button" value="淡出" />
</body>
</html>
show/hide 是從左上角開始,透過改變寬高把元素「拉開」或「壓扁」,因此版面中的其他元素會被逐步推開或拉近。
fadeIn/fadeOut 則是改變 opacity,元素佔的空間從頭到尾不變,只是漸漸顯現或消失。
選哪一種取決於你要不要讓版面「讓位」。圖片展開式閱讀用 show/hide 較合適;而 lightbox、提示訊息這類疊在內容上的浮層,用 fade 系列才不會把背後的排版推來推去。
第一,動畫時間 5000 與 2000 毫秒是為了方便觀察效果,實際使用請調到 200 ~ 400 毫秒之間,太慢會讓人以為程式當掉了。
第二,若使用者連續快速點擊,動畫會堆進佇列依序播放。加上 .stop(true, true) 可讓每次點擊都立即接管:
$('#Button1').click(function () {
$('#img1').stop(true, true).show(400);
});
另外,四個按鈕各自綁定 show/hide/fade 顯得有點囉嗦。若目的只是「一個按鈕來回切換」,用 $('#img1').toggle(400) 或 fadeToggle(400) 一行就能取代,不必維護四個事件。