滑鼠移入橙色區塊,文字從 12px 以 100ms 間隔逐漸放大至 42px,形成放大動畫。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head><meta charset="utf-8"><title>JS 文字放大效果</title>
<script>
var n = 12; // 初始字體大小
function chanTxt() {
var obj = document.getElementById("test");
if (n <= 42) {
obj.style.fontSize = n + "px";
}
n++;
}
</script></head>
<body>
滑鼠經過橙色區域
<div id="test"
onmouseover="setInterval('chanTxt()',100)"
style="width:300px;height:50px;font-size:12px;line-height:50px;background:#f90;cursor:default;">
腳本之家
</div>
</body></html>
setInterval(chanTxt, 100)。if (n <= 42) 限制最大放大尺寸,超過則停止變大(但定時器仍在運行,建議加 clearInterval)。font-size:12px 設定初始值,line-height:50px 垂直置中。<script>
var timer = null, n = 12;
function startGrow() {
if (timer) return; // 防止重複啟動
timer = setInterval(function() {
var el = document.getElementById("test");
if (n <= 42) { el.style.fontSize = n + "px"; n++; }
else { clearInterval(timer); timer = null; n = 12; } // 重置
}, 100);
}
function resetSize() {
clearInterval(timer); timer = null; n = 12;
document.getElementById("test").style.fontSize = "12px";
}
</script>
<div id="test" onmouseover="startGrow()" onmouseout="resetSize()" ...>腳本之家</div>
<style>
.zoom-text { font-size:12px; transition: font-size 3s linear; }
.zoom-text:hover { font-size:42px; }
</style>
<div class="zoom-text" style="width:300px;height:50px;line-height:50px;background:#f90;">腳本之家</div>
優點:GPU 加速、無阻塞、語意清晰、可維護性極高。
此範例展示早期 JS 動畫「定時器 + 樣式累加」的基本范式。理解其邏輯有助於閱讀舊代碼,但新專案請優先使用 CSS Transition/Animation 或 Web Animations API,獲得更流暢、高效能、無障礙的動畫體驗。