萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 文字放大動畫:onmouseover 觸發 setInterval 動態修改 font-size

效果描述

滑鼠移入橙色區塊,文字從 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>

關鍵點分析

  • 全域變數 n:記錄當前字體大小,每次遞增 1px。
  • setInterval('chanTxt()', 100):字串形式傳遞函式名(舊寫法),每 100ms 執行一次。現代建議傳遞函式引用: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>

現代 CSS 唯一解法 (零 JS)

<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,獲得更流暢、高效能、無障礙的動畫體驗。

copyright © 萬盛學電腦網 all rights reserved