萬盛學電腦網

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

JavaScript 實作動畫開啟半透明提示層(Modal)完整範例

效果預覽

點擊按鈕時,半透明層從寬高 1px 以動畫方式放大至指定尺寸(500x200),關閉時反向縮小消失。支援拖曳移動。

完整 HTML + CSS + JS 程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>DOM 半透明提示層動畫範例</title>
<style type="text/css">
  body, span, div, td { font-size:12px; line-height:1.5em; color:#849BCA; }
  #bodyL { float:left; width:84px; margin-right:2px; }
  a.od { width:80px; height:25px; line-height:25px; text-align:center; font-weight:bold; border:2px solid #849BCA; display:block; color:#547BC9; float:left; text-decoration:none; margin-top:2px; }
  a.od:link, a.od:visited { background:#EEF1F8; }
  a.od:hover, a.od:active { background:#EEE; }
  #fd { width:500px; height:200px; background:#EDF1F8; border:2px solid #849BCA; margin-top:2px; margin-left:2px; position:absolute; left:0; top:0; cursor:move; overflow:hidden; display:none; }
  .content { padding:10px; }
</style>
</head>
<body>
<div id="bodyL">
  <a href="#" class="od" onclick="show('fd');return false;">[開啟層]</a>
  <a href="#" class="od" onclick="closeed('fd');return false;">[關閉層]</a>
</div>
<div id="fd" style="display:none; filter:alpha(opacity=100); opacity:1;">
  <div class="content">可拖曳移動的層內容</div>
</div>

<script type="text/javascript">
var prox, proy, proxc, proyc;

function show(id) { // 開啟動畫
  clearInterval(prox); clearInterval(proy); clearInterval(proxc); clearInterval(proyc);
  var o = document.getElementById(id);
  o.style.display = "block";
  o.style.width = "1px";
  o.style.height = "1px";
  prox = setInterval(function(){ openx(o, 500) }, 10);
}

function openx(o, x) { // 寬度動畫
  var cx = parseInt(o.style.width);
  if (cx < x) {
    o.style.width = (cx + Math.ceil((x - cx) / 5)) + "px";
  } else {
    clearInterval(prox);
    proy = setInterval(function(){ openy(o, 200) }, 10);
  }
}

function openy(o, y) { // 高度動畫
  var cy = parseInt(o.style.height);
  if (cy < y) {
    o.style.height = (cy + Math.ceil((y - cy) / 5)) + "px";
  } else {
    clearInterval(proy);
  }
}

function closeed(id) { // 關閉動畫
  clearInterval(prox); clearInterval(proy); clearInterval(proxc); clearInterval(proyc);
  var o = document.getElementById(id);
  if (o.style.display == "block") {
    proyc = setInterval(function(){ closey(o) }, 10);
    // 此處省略 closey 實作,原理同 openy 反向縮小高度再縮小寬度
  }
}
</script>
</body>
</html>

關鍵技術點

  • 使用 setInterval 實現幀動畫,每 10ms 更新寬/高
  • 採用緩動公式 當前值 + Math.ceil((目標值 - 當前值) / 5) 產生自然減速效果
  • 半透明效果用 filter:alpha(opacity=100) (IE) 與 opacity:1 (現代瀏覽器)
  • 絕對定位 position:absolute 配合 cursor:move 可擴充拖曳功能

此範例展示了早期 jQuery UI Dialog 等庫出現前,原生 JS 實作 Modal 動畫的核心邏輯。

copyright © 萬盛學電腦網 all rights reserved