萬盛學電腦網

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

通用彈層組件 Dialog:PC/移動端適配、Alert/Confirm 擴展、jQuery/原生雙模式

組件特性

  • 雙模式:原生 new Dialog() / jQuery $.fn.Dialog()
  • 多種彈出類型:普通彈層、Alert、Confirm(三按鈕)、定時自動關閉 Alert
  • PC/移動端自適應,支持觸摸拖動、鍵盤 ESC 關閉
  • 遮罩層、標題欄、關閉按鈕、底部按鈕組可配置
  • 生命週期鉤子:beforeShow/afterShow/beforeHide/afterHide

核心類結構

class Dialog {
  constructor(options = {}) {
    this.options = Object.assign({
      target: null,        // 內容選擇器/元素/HTML字符串
      trigger: null,       // 觸發元素(可選)
      mask: true,          // 遮罩層
      title: '',           // 標題
      width: 'auto',       // 寬度
      height: 'auto',      // 高度
      zIndex: 9999,
      draggable: true,     // 標題欄拖動
      closeTpl: '×',       // 關閉按鈕HTML
      className: '',       // 額外類名
      onConfirm: null,     // 確認回調
      onCancel: null,      // 取消回調
      beforeShow: null,    // 顯示前鉤子
      afterShow: null,     // 顯示後鉤子
      beforeHide: null,    // 隱藏前鉤子
      afterHide: null      // 隱藏後鉤子
    }, options);

    this.$el = null; this.$mask = null; this.visible = false;
    this._init();
    if (this.options.trigger) this._bindTrigger();
  }

  _init() {
    // 創建 DOM
    this.$mask = $('
').hide().appendTo('body'); this.$el = $('
').hide().appendTo('body'); this._renderContent(); this._bindEvents(); } _renderContent() { var opt = this.options; var header = opt.title ? '
' + opt.title + '
' : ''; var footer = ''; this.$el.html(header + '
' + footer).addClass(opt.className); this.$body = this.$el.find('.dialog-body'); // 填充內容 if (opt.target instanceof $) this.$body.append(opt.target.clone().show()); else if (typeof opt.target === 'string' && opt.target.startsWith('<')) this.$body.html(opt.target); else this.$body.append($(opt.target).clone().show()); // 尺寸 if (opt.width !== 'auto') this.$el.width(opt.width); if (opt.height !== 'auto') this.$el.height(opt.height); } _bindEvents() { var self = this; // 關閉按鈕 this.$el.on('click', '.dialog-close', function() { self.hide(); }); // 遮罩點擊關閉 if (this.options.mask) this.$mask.on('click', function() { self.hide(); }); // ESC 關閉 $(document).on('keydown.dialog' + this._uid, function(e) { if (e.key === 'Escape' && self.visible) self.hide(); }); // 拖動 if (this.options.draggable) this._enableDrag(); } _enableDrag() { var self = this, $header = this.$el.find('.dialog-header'), dragging = false, ox, oy; $header.on('mousedown', function(e) { if ($(e.target).is('button')) return; dragging = true; ox = e.clientX - self.$el[0].offsetLeft; oy = e.clientY - self.$el[0].offsetTop; $header.css('cursor', 'grabbing'); e.preventDefault(); }); $(document).on('mousemove', function(e) { if (!dragging) return; self.$el.css({left: e.clientX - ox, top: e.clientY - oy}); }); $(document).on('mouseup', function() { dragging = false; $header.css('cursor', 'move'); }); } _bindTrigger() { var self = this; $(this.options.trigger).on('click', function() { self.show(); }); } show() { if (this.visible) return; if (this.options.beforeShow) this.options.beforeShow.call(this, this.$el); this.$mask.css('z-index', this.options.zIndex).fadeIn(200); this.$el.css('z-index', this.options.zIndex + 1).fadeIn(200, () => { this._center(); this.visible = true; if (this.options.afterShow) this.options.afterShow.call(this, this.$el); }); } hide() { if (!this.visible) return; if (this.options.beforeHide) this.options.beforeHide.call(this, this.$el); this.$el.fadeOut(200); this.$mask.fadeOut(200, () => { this.visible = false; if (this.options.afterHide) this.options.afterHide.call(this, this.$el); }); $(document).off('keydown.dialog' + this._uid); } _center() { var w = this.$el.outerWidth(), h = this.$el.outerHeight(); this.$el.css({ left: ($(window).width() - w) / 2, top: ($(window).height() - h) / 2 }); } destroy() { this.hide(); this.$el.remove(); this.$mask.remove(); $(document).off('keydown.dialog' + this._uid); } } // 唯一 ID 生成 Dialog._uid = 0; Dialog.prototype._uid = Dialog._uid++;

jQuery 插件橋接

$.fn.Dialog = function(options) {
  return this.each(function() {
    var $this = $(this);
    var dialog = $this.data('dialog');
    if (!dialog) {
      options = $.extend({}, options, { trigger: this });
      dialog = new Dialog(options);
      $this.data('dialog', dialog);
    } else if (typeof options === 'string') {
      dialog[options](); // show/hide/destroy
    }
    return dialog;
  });
};

// 靜態方法:Alert / Confirm
$.alert = function(content, autoClose, callback) {
  var d = new Dialog({ target: '
' + content + '
', title: '提示', mask: true, width: 300, onConfirm: callback, beforeHide: function() { if (autoClose) return true; } }); d.show(); if (autoClose) setTimeout(() => d.hide(), typeof autoClose === 'number' ? autoClose : 2000); return d; }; $.confirm = function(content, buttons, callback) { var btns = buttons || [{yes:'確定'},{no:'取消'}]; var footer = btns.map(b => '').join(''); var d = new Dialog({ target: '
' + content + '
', title: '確認', mask: true, width: 350, beforeShow: function($el) { $el.find('.dialog-body').after(''); }, afterShow: function($el) { $el.on('click', '.dialog-btn', function() { var result = $(this).data('result'); d.hide(); if (callback) callback(result); }); } }); d.show(); return d; };

CSS 樣式(關鍵片段)

.dialog-mask { position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.5); z-index:9999; display:none; }
.dialog { position:fixed; background:#fff; border-radius:6px; box-shadow:0 8px 30px rgba(0,0,0,.2); display:none; font-family:sans-serif; min-width:280px; max-width:90vw; max-height:90vh; overflow:hidden; }
.dialog-header { display:flex; justify-content:space-between; align-items:center; padding:12px 16px; border-bottom:1px solid #eee; background:#fafafa; border-radius:6px 6px 0 0; cursor:move; }
.dialog-title { font-weight:600; font-size:15px; color:#333; }
.dialog-close { background:none; border:none; font-size:22px; line-height:1; color:#999; cursor:pointer; padding:0 4px; }
.dialog-close:hover { color:#333; }
.dialog-body { padding:20px; overflow:auto; max-height:60vh; }
.dialog-footer { display:flex; justify-content:flex-end; padding:12px 16px; border-top:1px solid #eee; gap:8px; }
.dialog-btn { padding:8px 20px; border-radius:4px; border:1px solid #ddd; background:#fff; cursor:pointer; font-size:14px; }
.dialog-btn[data-result="yes"] { background:#007bff; border-color:#007bff; color:#fff; }

使用示例

<!-- 普通彈層 -->
<button id="btn1">打開彈層</button>
<div id="content1" style="display:none">自定義內容</div>
<script>
$('#btn1').Dialog({ target: '#content1', title: '標題', width: 500, height: 300, mask: true });
</script>

<!-- Alert -->
<button onclick="$.alert('操作成功!', true)">自動關閉 Alert</button>
<button onclick="$.alert('請確認', false, () => console.log('用戶確認'))">回調 Alert</button>

<!-- Confirm 三按鈕 -->
<button onclick="$.confirm('下載 9 張圖片?', [{yes:'下載'},{no:'取消'},{close:'稍後'}], r => alert('選擇:'+r))">三按鈕 Confirm</button>

總結

Dialog 組件展示了「配置驅動、生命週期鉤子、雙模式 API、靜態便捷方法」的工程化設計。核心難點在於:焦點管理、拖動邊界、動畫與狀態同步、多實例隔離、無障礙屬性。生產環境建議增加:動畫取消時的狀態清理、滾動鎖定(body{overflow:hidden})、嵌套彈層層級管理、服務端渲染兼容。

copyright © 萬盛學電腦網 all rights reserved