萬盛學電腦網

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

JavaScript 動態調整元素尺寸:瞬間縮放與漸變動畫兩種實作

本文示範兩種 JavaScript 動態改變 <div> 尺寸的方式:一鍵瞬間設定目標尺寸,以及使用 setInterval 逐步漸變的動畫效果。並特別說明 style.width 讀取時機與 CSS class 衝突的常見坑點。

方法一:瞬間設定尺寸

直接指定 style.width 與 style.height,適合不需要動畫過渡的場景。

function zoomDiv() {
    var div = document.getElementById("divMain");
    div.style.width = "200px";
    div.style.height = "200px";
}

方法二:漸變動畫效果

使用 setInterval 每 100ms 遞增 1px,直到達到目標尺寸再清除計時器。

var intervalId;

function showDiv() {
    intervalId = setInterval(incrementSize, 100);
}

function incrementSize() {
    var div = document.getElementById("divMain2");
    // 關鍵:必須用 inline style 寫寬高,否則 style.width 讀不到值
    var w = parseInt(div.style.width) || 0;
    var h = parseInt(div.style.height) || 0;
    
    w++; h++;
    
    if (w >= 200) {
        clearInterval(intervalId);
        return;
    }
    
    div.style.width = w + "px";
    div.style.height = h + "px";
}

重要坑點:inline style vs CSS class

程式碼註解已提示:若元素尺寸只在 CSS class 定義,element.style.width 會回傳空字串。必須在 HTML 直接寫 style="width:10px;height:100px",或在 JS 初始化時先寫入 inline style。

<!-- 錯誤:style.width 讀不到 -->
<div id="divMain" class="divMain">...</div>

<!-- 正確:inline style 可被 JS 讀寫 -->
<div id="divMain2" style="width:10px;height:100px;background:red">...</div>

現代化改寫:CSS Transition + JS 觸發

現代瀏覽器建議將動畫交給 CSS,JS 僅負責切換目標狀態,效能更好、程式碼更簡潔。

<style>
.resize-box {
    width: 10px;
    height: 100px;
    background: red;
    transition: width 1s ease, height 1s ease; /* CSS 處理動畫 */
}
</style>

<div id="box" class="resize-box">內容</div>
<button onclick="expand()">展開</button>
<button onclick="collapse()">收合</button>

<script>
function expand() {
    const el = document.getElementById('box');
    el.style.width = '200px';
    el.style.height = '200px';
}

function collapse() {
    const el = document.getElementById('box');
    el.style.width = '10px';
    el.style.height = '100px';
}
</script>

進階:Web Animations API(原生 JS 動畫控制)

若需 JS 精確控制播放/暫停/反向,可使用原生 Element.animate():

const box = document.getElementById('box');

function animateSize(targetW, targetH, duration = 1000) {
    return box.animate([
        { width: box.style.width || '10px', height: box.style.height || '100px' },
        { width: targetW + 'px', height: targetH + 'px' }
    ], {
        duration,
        easing: 'ease-in-out',
        fill: 'forwards' // 結束保持終狀態
    });
}

// 使用
const anim = animateSize(200, 200);
anim.finished.then(() => console.log('動畫完成'));

// 可暫停/反向
// anim.pause();
// anim.reverse();

總結建議

  • 簡單漸變:CSS Transition 最省力、效能最好
  • 需程式控制播放狀態:Web Animations API 原生、無依賴
  • 舊專案維護/特殊邏輯:setInterval 手動遞增仍可用,但注意清除計時器與 inline style 前置
copyright © 萬盛學電腦網 all rights reserved