萬盛學電腦網

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

原生 JavaScript 實現同頁多元素多屬性並發動畫:統一緩動引擎支援 width/height/fontSize/opacity

場景

同一頁面多個元素,各自綁定不同屬性動畫(寬度、高度、字號、透明度),互不干擾,同時運行。

統一獲取樣式工具

function getStyle(el, prop) {
  return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el, false)[prop];
}

通用動畫函數(支援任意數值屬性)

function startRun(el, attr, target) {
  clearInterval(el.timer); // 每元素獨立 timer
  el.timer = setInterval(function() {
    var cur = attr === 'opacity'
      ? Math.round(parseFloat(getStyle(el, attr)) * 100)
      : parseInt(getStyle(el, attr));
    var speed = (target - cur) / 8;
    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

    if (cur === target) {
      clearInterval(el.timer);
    } else {
      if (attr === 'opacity') {
        el.style.filter = 'alpha(opacity=' + (cur + speed) + ')';
        el.style.opacity = (cur + speed) / 100;
      } else {
        el.style[attr] = cur + speed + 'px';
      }
    }
  }, 30);
}

多元素綁定示例

<style>
  #runs li { width: 80px; height: 80px; background: #06c; list-style: none; margin: 10px; border: 1px solid #000; filter: alpha(opacity=30); opacity: 0.3; }
</style>
<ul id="runs">
  <li style="top:0">1</li>
  <li style="top:90px">2</li>
  <li style="top:180px">3</li>
  <li style="top:270px">4</li>
</ul>

<script>
window.onload = function() {
  var items = document.getElementById('runs').getElementsByTagName('li');

  items[0].onmouseover = function() { startRun(this, 'width', 300); };
  items[0].onmouseout  = function() { startRun(this, 'width', 80); };

  items[1].onmouseover = function() { startRun(this, 'height', 300); };
  items[1].onmouseout  = function() { startRun(this, 'height', 80); };

  items[2].onmouseover = function() { startRun(this, 'fontSize', 50); };
  items[2].onmouseout  = function() { startRun(this, 'fontSize', 14); };

  items[3].onmouseover = function() { startRun(this, 'opacity', 100); };
  items[3].onmouseout  = function() { startRun(this, 'opacity', 30); };
};
</script>

關鍵點總結

  1. 每元素獨立 timer:el.timer 掛在元素上,互不衝突。
  2. 統一數值解析:opacity 用 parseFloat * 100 + Math.round,其它用 parseInt 去單位。
  3. 緩動公式:(target - cur) / 8 形成越來越慢的緩動效果,ceil/floor 保證能到達終點。
  4. 屬性名直接用於 style:el.style[attr] 動態設置,支援駝峰屬性名(fontSize)。

擴展:同時動畫多屬性

function animateMulti(el, props, duration, easing, cb) {
  // props: {width: 300, opacity: 100, ...}
  // 內部為每屬性創建獨立定時器或用 rAF 統一幀循環
}

實戰建議封裝為類,管理動畫隊列、暫停/恢復、完成回調。

copyright © 萬盛學電腦網 all rights reserved