萬盛學電腦網

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

原生 JavaScript 實現新浪微博式內容漸顯動畫:插入置頂 + 高度/透明度雙階段動畫

效果拆解

  1. 點擊發布 → 新內容插入列表**最頂部**
  2. 第一階段:高度從 0 動畫到實際高度(撐開佔位)
  3. 第二階段:透明度從 0 動畫到 1(淡入內容)
  4. 整體呈現「由無到有、由淡入實」的絲滑感

關鍵技術點

  • insertBefore(new, firstChild) 實現置頂插入
  • offsetHeight 獲取實際高度,先置 0 再動畫
  • 自定義緩動動畫函數 startRun(el, attr, target, callback) 支援鏈式調用
  • getComputedStyle / currentStyle 兼容獲取當前樣式值

完整可運行代碼

<!DOCTYPE html>
<html>
<head>
  <meta charset="gb2312">
  <title>微博式漸顯</title>
  <style>
    body,ul,li{margin:0;padding:0;font:12px/1.5 Arial;}
    #list{width:400px;margin:10px auto;}
    #list li{list-style:none;padding:5px 0;overflow:hidden;border-bottom:1px dotted #ccc;filter:alpha(opacity=0);opacity:0;vertical-align:middle;}
  </style>
</head>
<body>
  <textarea id="con" cols="50" rows="5"></textarea>
  <input id="btn" type="button" value="發布">
  <ul id="list"></ul>

  <script>
    window.onload = function() {
      var btn = document.getElementById('btn');
      var con = document.getElementById('con');
      var list = document.getElementById('list');

      btn.onclick = function() {
        var text = con.value.trim();
        if (!text) return;
        con.value = '';

        var li = document.createElement('li');
        li.innerHTML = text;
        li.style.height = '0'; // 初始高度 0

        // 置頂插入
        var first = list.getElementsByTagName('li')[0];
        first ? list.insertBefore(li, first) : list.appendChild(li);

        // 獲取實際高度(需先加入文檔流才能測量)
        var targetH = li.offsetHeight;
        li.style.height = '0';

        // 階段1:高度展開 → 階段2:透明度淡入
        startRun(li, 'height', targetH, function() {
          startRun(li, 'opacity', 100);
        });
      };
    };

    // 通用緩動動畫引擎
    function getStyle(el, prop) {
      return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el, false)[prop];
    }
    function startRun(el, attr, target, cb) {
      clearInterval(el.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);
          cb && cb();
        } 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);
    }
  </script>
</body>
</html>

現代化重構(CSS Transition + requestAnimationFrame)

<style>
  #list li { transition: height .3s ease, opacity .3s ease .3s; opacity: 0; height: 0; overflow: hidden; }
  #list li.show { height: auto; opacity: 1; } /* height:auto 無法過渡,見下文 */
</style>

<script>
btn.onclick = function() {
  var li = document.createElement('li');
  li.textContent = con.value.trim(); con.value = '';
  if (!text) return;
  var first = list.querySelector('li');
  first ? list.insertBefore(li, first) : list.appendChild(li);

  // 強制回流讀取高度
  var h = li.scrollHeight;
  li.style.height = h + 'px'; // 顯式高度可過渡
  li.style.opacity = 1;
  // 動畫結束後改為 auto 防止內容變化截斷
  li.addEventListener('transitionend', function fn() {
    li.style.height = 'auto';
    li.removeEventListener('transitionend', fn);
  });
};
</script>

注意:CSS 無法直接過渡 height: 0 → auto,需用 JS 測量後設定具體像素值,動畫結束再改回 auto。

copyright © 萬盛學電腦網 all rights reserved