萬盛學電腦網

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

JavaScript 通用 Loading 動畫組件實現(支持自定義容器、回調、多實例)

組件設計目標

  • 零依賴(可選 jQuery 輔助 DOM)
  • 支持任意容器元素(非全屏強制)
  • 可配置位置、大小、動畫時長
  • 提供啟動/停止/銷毀完整生命周期
  • 支持多實例並發

核心實現(原生 JS 版,推薦)

class LoadingOverlay {
  /**
   * @param {HTMLElement|string} container - 掛載容器
   * @param {Object} options
   */
  constructor(container, options = {}) {
    this.container = typeof container === 'string' 
      ? document.querySelector(container) 
      : container;
    if (!this.container) throw new Error('Container not found');
    
    this.options = Object.assign({
      size: 32,           // 圖標尺寸
      color: '#007bff',   // 主色調
      bgColor: 'rgba(255,255,255,0.8)', // 背景色
      zIndex: 1000,
      text: '加載中...',
      fontSize: '14px',
      spinnerType: 'border', // 'border' | 'dots' | 'pulse'
      onStart: null,
      onStop: null
    }, options);
    
    this._init();
  }
  
  _init() {
    // 確保容器可定位
    const style = getComputedStyle(this.container);
    if (style.position === 'static') {
      this.container.style.position = 'relative';
    }
    
    // 創建遮罩層
    this.overlay = document.createElement('div');
    this.overlay.className = 'loading-overlay';
    this.overlay.style.cssText = `
      position: absolute; inset: 0; 
      background: ${this.options.bgColor};
      z-index: ${this.options.zIndex};
      display: flex; align-items: center; justify-content: center;
      flex-direction: column; gap: 8px;
      opacity: 0; visibility: hidden;
      transition: opacity 0.2s, visibility 0.2s;
    `;
    
    // 創建 Spinner
    this.spinner = this._createSpinner();
    this.overlay.appendChild(this.spinner);
    
    // 創建文本
    if (this.options.text) {
      this.textEl = document.createElement('div');
      this.textEl.style.cssText = `
        color: ${this.options.color}; 
        font-size: ${this.options.fontSize};
        white-space: nowrap;
      `;
      this.textEl.textContent = this.options.text;
      this.overlay.appendChild(this.textEl);
    }
    
    this.container.appendChild(this.overlay);
    
    // 強制回流觸發動畫
    this.overlay.offsetHeight;
  }
  
  _createSpinner() {
    const { size, color, spinnerType } = this.options;
    const el = document.createElement('div');
    el.style.cssText = `width: ${size}px; height: ${size}px;`;
    
    if (spinnerType === 'border') {
      el.style.cssText += `
        border: 3px solid ${color}44; 
        border-top-color: ${color};
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
      `;
      // 注入 keyframes(僅首次)
      if (!document.getElementById('loading-spinner-style')) {
        const style = document.createElement('style');
        style.id = 'loading-spinner-style';
        style.textContent = '@keyframes spin { to { transform: rotate(360deg); } }';
        document.head.appendChild(style);
      }
    } else if (spinnerType === 'dots') {
      el.style.cssText += 'display: flex; justify-content: space-between;';
      for (let i = 0; i < 3; i++) {
        const dot = document.createElement('div');
        dot.style.cssText = `
          width: ${size/4}px; height: ${size/4}px; 
          background: ${color}; border-radius: 50%;
          animation: bounce 0.6s ease-in-out infinite both;
          animation-delay: ${i * 0.15}s;
        `;
        el.appendChild(dot);
      }
      if (!document.getElementById('loading-dots-style')) {
        const style = document.createElement('style');
        style.id = 'loading-dots-style';
        style.textContent = `
          @keyframes bounce { 0%,80%,100% { transform: scale(0); } 40% { transform: scale(1); } }
        `;
        document.head.appendChild(style);
      }
    }
    return el;
  }
  
  show() {
    this.overlay.style.opacity = '1';
    this.overlay.style.visibility = 'visible';
    // 禁用容器內可聚焦元素
    this._toggleInteractive(false);
    if (this.options.onStart) this.options.onStart(this);
  }
  
  hide() {
    this.overlay.style.opacity = '0';
    this.overlay.style.visibility = 'hidden';
    this._toggleInteractive(true);
    if (this.options.onStop) this.options.onStop(this);
  }
  
  _toggleInteractive(enable) {
    const focusable = this.container.querySelectorAll(
      'button, input, select, textarea, a[href], [tabindex]:not([tabindex="-1"])'
    );
    focusable.forEach(el => {
      if (!enable) el.dataset._wasDisabled = el.disabled;
      el.disabled = !enable;
      if (enable && el.dataset._wasDisabled === 'true') el.disabled = true;
    });
  }
  
  destroy() {
    this.hide();
    this.overlay.remove();
    this.container = this.overlay = this.spinner = this.textEl = null;
  }
  
  // 靜態工廠方法
  static create(container, options) {
    return new LoadingOverlay(container, options);
  }
}

// 導出(支持 CommonJS/ESM/全局)
if (typeof module !== 'undefined') module.exports = LoadingOverlay;
else if (typeof define === 'function') define([], () => LoadingOverlay);
else window.LoadingOverlay = LoadingOverlay;

使用示例

基礎用法

// 初始化(頁面加載時創建,復用實例)
const loading = LoadingOverlay.create('#form-container', {
  text: '提交中...',
  spinnerType: 'dots'
});

// 按鈕點擊觸發
$('#submit-btn').click(async function() {
  const btn = this;
  btn.disabled = true;
  loading.show();
  
  try {
    await submitForm(); // 異步請求
    showToast('成功');
  } catch (err) {
    showToast('失敗: ' + err.message);
  } finally {
    loading.hide();
    btn.disabled = false;
  }
});

全屏 Loading(掛載 body)

const fullLoading = LoadingOverlay.create('body', {
  bgColor: 'rgba(0,0,0,0.5)',
  size: 48,
  text: '數據加載中...',
  zIndex: 9999
});

// 路由切換時
router.beforeEach((to, from, next) => {
  fullLoading.show();
  next();
});
router.afterEach(() => {
  setTimeout(() => fullLoading.hide(), 300); // 留白過渡
});

多實例獨立控制

const tableLoading = LoadingOverlay.create('#data-table');
const chartLoading = LoadingOverlay.create('#chart-container');

Promise.all([
  fetchTableData().then(() => tableLoading.hide()),
  fetchChartData().then(() => chartLoading.hide())
]).catch(err => {
  tableLoading.hide();
  chartLoading.hide();
  handleError(err);
});

jQuery 適配器(兼容舊代碼)

$.fn.loading = function(options) {
  return this.each(function() {
    var $el = $(this);
    var instance = $el.data('loading-instance');
    
    if (options === 'hide' || options === 'destroy') {
      if (instance) {
        instance[options]();
        if (options === 'destroy') $el.removeData('loading-instance');
      }
      return;
    }
    
    if (!instance) {
      instance = LoadingOverlay.create(this, options);
      $el.data('loading-instance', instance);
    }
    instance.show();
  });
};

// 使用
$('#my-form').loading({ text: '保存中...' });
$('#my-form').loading('hide');
$('#my-form').loading('destroy');

CSS 純樣式方案(零 JS 運行時)

.loading-mask {
  position: relative;
}
.loading-mask::before {
  content: '';
  position: absolute; inset: 0;
  background: rgba(255,255,255,0.8);
  z-index: 10;
  display: flex; align-items: center; justify-content: center;
  opacity: 0; visibility: hidden;
  transition: 0.2s;
}
.loading-mask::after {
  content: '加載中...';
  position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
  color: #007bff; font-size: 14px; white-space: nowrap;
  z-index: 11;
  opacity: 0; visibility: hidden;
  transition: 0.2s;
}
.loading-mask.active::before,
.loading-mask.active::after {
  opacity: 1; visibility: visible;
}
.loading-mask.active::before {
  background-image: url("data:image/svg+xml,");
  background-position: center;
  background-repeat: no-repeat;
  background-size: 32px;
}
// 只需切換 class
document.getElementById('container').classList.add('loading-mask', 'active');
// 結束
document.getElementById('container').classList.remove('active');
copyright © 萬盛學電腦網 all rights reserved