萬盛學電腦網

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

JavaScript 實現視窗從中心向上下展開動畫

頁面載入時,以兩個覆蓋層從畫面中心向上下展開,露出內容。屬於早期「進場動畫」常見效果,現代建議改用 CSS Animation 實現,效能更佳且可控性更高。

原理說明

  • 建立兩個絕對定位 `
    `,分別佔據畫面上半部、下半部
  • 初始高度為畫面一半,上層 `bottom` 從中心向上縮減,下層 `top` 從中心向下縮減
  • 使用 `setInterval` 逐幀更新 `clip`(IE)或 `height`(現代瀏覽器)

現代化 CSS 實作(推薦)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>中心展開進場動畫</title>
<style>
  .split { position:fixed; left:0; width:100%; height:50%; background:#336699; z-index:9999; }
  .top { top:0; transform-origin: bottom; animation: expandUp 0.8s cubic-bezier(0.25,0.46,0.45,0.94) forwards; }
  .bottom { bottom:0; transform-origin: top; animation: expandDown 0.8s cubic-bezier(0.25,0.46,0.45,0.94) forwards; }
  @keyframes expandUp { to { transform: scaleY(0); } }
  @keyframes expandDown { to { transform: scaleY(0); } }
  .content { position:relative; z-index:1; padding:2rem; }
</style>
</head>
<body>
  <div class="split top"></div>
  <div class="split bottom"></div>
  <div class="content">
    <h1>內容區域</h1>
    <p>動畫結束後自動隱藏分割層,顯示正常內容。</p>
  </div>
  <script>
    // 動畫結束後移除分割層,避免阻擋互動
    document.querySelector('.top').addEventListener('animationend', function() {
      this.remove();
      document.querySelector('.bottom').remove();
    });
  </script>
</body>
</html>

原始 JS 版本(教學參考)

// 僅供理解早期實作邏輯,實務請用 CSS 版
var speed = 20;
var topDiv = document.getElementById('top');
var bottomDiv = document.getElementById('bottom');
var clipBottom = document.body.offsetHeight/2;
var clipTop = 0;

function openIt() {
  clipBottom -= speed;
  topDiv.style.clip = 'rect(0 auto ' + clipBottom + 'px 0)';
  clipTop += speed;
  bottomDiv.style.clip = 'rect(' + clipTop + 'px auto auto 0)';
  if (clipBottom <= 0) clearInterval(timer);
}
var timer = setInterval(openIt, 30);

無障礙注意

  • 尊重 `@media (prefers-reduced-motion: reduce)` 停用動畫
  • 動畫不應阻礙內容閱讀,必要時提供「跳過動畫」按鈕
copyright © 萬盛學電腦網 all rights reserved