萬盛學電腦網

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

JavaScript 動畫效果開啟/關閉層(從中心點縮放展開)

效果描述

點擊「開啟」按鈕,隱藏層從中心點(10×10px)以緩動動畫同時放大寬度與高度至 400px;點擊「關閉」反向縮小至 10px 後隱藏。視覺類似 Lightbox 開啟/關閉動畫。

核心動畫引擎

function XslideDown(obj, type, max, step) {
  if (!type) return;
  var t1 = type === 'height' ? 'marginTop' : 'marginLeft';
  var t2 = type === 'height' ? 'top' : 'left';
  XSetCss(obj, [t1, XgetOffset(obj)[t2] + 'px']);
  XSetCss(obj, [type, XgetOffset(obj)[type] + step + 'px']);
  if (XgetOffset(obj)[type] < max) {
    setTimeout(function() { XslideDown(obj, type, max, step); }, 10);
  } else { XSetCss(obj, [type, max]); }
}

function XslideUp(obj, type, min, step) {
  if (!type) return;
  var t1 = type === 'height' ? 'marginTop' : 'marginLeft';
  var t2 = type === 'height' ? 'top' : 'left';
  XSetCss(obj, [t1, XgetOffset(obj)[t2] + 'px']);
  XSetCss(obj, [type, XgetOffset(obj)[type] - step + 'px']);
  if (XgetOffset(obj)[type] > min) {
    setTimeout(function() { XslideUp(obj, type, min, step); }, 1);
  } else { XSetCss(obj, [type, min]); obj.style.display = 'none'; }
}

function XSetCss(obj, args) {
  if (args.constructor === Object) for (var k in args) if (obj.style[k] !== undefined) obj.style[k] = args[k];
  else if (args.constructor === Array && args.length === 2) obj.style[args[0]] = args[1];
}

function XgetOffset(obj) {
  return {
    height: obj.offsetHeight, width: obj.offsetWidth,
    top: parseInt((obj.parentNode.offsetHeight - obj.offsetHeight) / 2),
    left: parseInt((obj.parentNode.offsetWidth - obj.offsetWidth) / 2)
  };
}

呼叫方式

function XopenDiv(o) { o.style.display = 'block'; XslideDown(o, 'width', 400, 10); XslideDown(o, 'height', 400, 10); }
function XcloseDiv(o) { XslideUp(o, 'width', 10, 10); XslideUp(o, 'height', 10, 10); }

$('bt').onclick = function() { XopenDiv($('test')); };
$('bt1').onclick = function() { XcloseDiv($('test')); };

現代化重構:CSS Transform + Transition


.layer { transform: scale(0); transform-origin: center; transition: transform 0.3s ease; opacity: 0; pointer-events: none; }
.layer.open { transform: scale(1); opacity: 1; pointer-events: auto; }

// JS 僅切換 class
function toggleLayer(el) { el.classList.toggle('open'); }
  • GPU 加速、主執行緒不阻塞、程式碼極簡。
  • transform-origin: center 對應原版「中心點展開」視覺。
  • 支援 will-change: transform 進一步優化。
copyright © 萬盛學電腦網 all rights reserved