直接 click 就瞬間變大,看起來很生硬;把同一件事拆成十幾次微小的變化,就變成有呼吸感的動畫。核心工具是 setInterval,加上一個計數器控制要跑幾步。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>圖片的緩慢縮放</title>
<style>
#pic { width: 20%; }
.scale { margin-top: 12px; }
</style>
</head>
<body>
<div id="pic" style="width: 20%">
<img src="3.pic.jpg" style="width:100%;">
</div>
<div class="scale">
<button id="big">放大</button>
<button id="small">縮小</button>
</div>
<script>
window.onload = function () {
var btnBig = document.getElementById('big');
var btnSmall = document.getElementById('small');
var pic = document.getElementById('pic');
var MIN = 10, MAX = 50, STEP = 13; // 每 13ms 變動 1%
function resize(step) {
var width = parseInt(pic.style.width, 10);
var count = 0;
var timer = setInterval(function () {
width += step;
count++;
// 撞到上下限就收工
if (width <= MIN || width >= MAX) {
width = Math.min(Math.max(width, MIN), MAX);
pic.style.width = width + '%';
clearInterval(timer);
return;
}
pic.style.width = width + '%';
if (count >= 10) clearInterval(timer);
}, STEP);
}
btnBig.onclick = function () { resize(1); };
btnSmall.onclick = function () { resize(-1); };
};
</script>
</body>
</html>
1. 計數與邊界混在一起判斷。原本同時用 count == 10 和 i > 50 兩個條件,順序還顛倒,容易出現「還沒縮到下限就停了」或「一格都沒動」的狀況。改成每次先套用步長、再夾在 MIN/MAX 之間,行為就完全可預期。
2. 放大縮小邏輯重複。把差異(步長正負號)抽成參數,一份 resize 函式就夠,這也是較好的維護方式。
3. 圖片用 3.pic.jpg 這種檔名。記得換成自己的實際路徑,並加上 alt 屬性方便無障礙閱讀。
改用 requestAnimationFrame。setInterval 會被系統合併、也容易與畫面刷新不同步,rAF 會跟著顯示器刷新率走,看起來更順:
function animateTo(target) {
var start = parseInt(pic.style.width, 10);
var startTime = null, duration = 300;
function frame(now) {
if (!startTime) startTime = now;
var p = Math.min((now - startTime) / duration, 1);
pic.style.width = (start + (target - start) * p) + '%';
if (p < 1) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
用 CSS transition 更省事。如果只是單純放大縮小,一行 CSS 就足夠,不必寫 JS 計時器:
#pic {
width: 20%;
transition: width .3s ease;
}
#pic:hover { width: 50%; }
記住選擇的原則:狀態切換用 CSS transition,需要依序播放多段、或每格要做運算的動畫才用 JS 逐格控制。