利用 setTimeout 遞迴調整圖片 height 從 0 漸增至目標高度,搭配連結觸發動畫,形成「點擊展開」的視覺效果。屬早期 DHTML 動畫典型寫法。
<html>
<title>JS點擊鏈接後,慢慢展開隱藏著的圖片</title>
<body>
<script>
var b = 0, c = true;
function fade() {
if (document.all); // 無作用陳述式
if (c == true) b += 3;
if (b > 294) c = false;
u.width = 394;
u.height = b;
setTimeout("fade()", 1);
}
</script>
<p align="center"><a href="javascript:"><img src="/images/3.jpg" name="u" width="0" height="0" border="0" onclick="javascript:window.open(this.src);" style="cursor:pointer;" /></a></p>
<p align="center"><a href="javascript:" onClick="fade()">點擊展開圖片</a></p>
</body>
</html>
document.all 判斷無實際作用。setTimeout("fade()", 1) 效能差且難除錯,應改用函式參考。width=0 height=0 會導致佈局塌陷,建議用 visibility:hidden 或 opacity:0 搭配容器固定尺寸。<style>
.expand-img { width: 394px; height: 0; overflow: hidden; transition: height 0.5s ease; }
.expand-img.show { height: 294px; }
</style>
<img id="targetImg" class="expand-img" src="/images/3.jpg" alt="" />
<button onclick="toggleExpand()">點擊展開/收合</button>
<script>
function toggleExpand() {
document.getElementById('targetImg').classList.toggle('show');
}
</script>
優點:動畫交給瀏覽器原生處理、程式碼可維護、無硬編碼尺寸(可改用 max-height 配合 scrollHeight 實現自適應高度)。