萬盛學電腦網

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

jQuery 彈出層組件核心代碼解析與擴展實戰

前言

彈出層是 Web 應用高頻組件。本文解析一個基於 jQuery 的彈出層核心實現,涵蓋觸發器綁定、遮罩層、動畫效果、拖拽移動、關閉銷毀,並提供擴展插件化思路。

核心類結構

var PopupLayer = function(options) {
    this.settings = $.extend({
        trigger: null,        // 觸發器選擇器
        popupBlk: null,       // 彈層選擇器
        closeBtn: null,       // 關閉按鈕選擇器
        useOverlay: true,     // 是否顯示遮罩
        useFx: true,          // 是否啟用動畫
        offsets: { x: 0, y: 0 } // 相對觸發器偏移
    }, options);
    
    this.trigger = $(this.settings.trigger);
    this.popupLayer = $(this.settings.popupBlk);
    this.closeBtn = $(this.settings.closeBtn);
    this.overlay = null;
    this.isOpen = false;
    
    this.init();
};

PopupLayer.prototype = {
    init: function() {
        var self = this;
        
        // 綁定觸發器
        this.trigger.on('click', function(e) {
            e.stopPropagation();
            self.open();
        });
        
        // 綁定關閉按鈕
        this.closeBtn.on('click', function(e) {
            e.stopPropagation();
            self.close();
        });
        
        // 遮罩點擊關閉
        if (this.settings.useOverlay) {
            $(document).on('click', function(e) {
                if (self.isOpen && !$(e.target).closest(self.popupLayer).length) {
                    self.close();
                }
            });
        }
    },
    
    open: function() {
        if (this.isOpen) return;
        
        // 創建遮罩
        if (this.settings.useOverlay) {
            this.overlay = $('').appendTo('body');
            this.overlay.css({
                position: 'fixed', top: 0, left: 0, width: '100%', height: '100%',
                background: '#000', opacity: 0.5, zIndex: 9998
            });
        }
        
        // 定位彈層
        this.position();
        
        // 動畫顯示
        if (this.settings.useFx) {
            this.popupLayer.css({ opacity: 0.3, display: 'block' }).animate({
                opacity: 1,
                left: (($(window).width() - this.popupLayer.outerWidth()) / 2) + this.settings.offsets.x,
                top: (($(window).height() - this.popupLayer.outerHeight()) / 2 + $(window).scrollTop()) + this.settings.offsets.y
            }, 300);
        } else {
            this.popupLayer.show();
        }
        
        this.isOpen = true;
        $(window).on('resize.popup', $.proxy(this.position, this));
    },
    
    close: function() {
        if (!this.isOpen) return;
        
        if (this.settings.useFx) {
            this.popupLayer.animate({
                opacity: 0,
                left: this.trigger.offset().left,
                top: this.trigger.offset().top
            }, 200, $.proxy(function() {
                this.popupLayer.hide().css('opacity', 1);
                this.cleanup();
            }, this));
        } else {
            this.popupLayer.hide();
            this.cleanup();
        }
    },
    
    position: function() {
        if (!this.isOpen) return;
        var left = ($(window).width() - this.popupLayer.outerWidth()) / 2 + this.settings.offsets.x;
        var top = ($(window).height() - this.popupLayer.outerHeight()) / 2 + $(window).scrollTop() + this.settings.offsets.y;
        this.popupLayer.css({ left: left, top: top });
    },
    
    cleanup: function() {
        if (this.overlay) { this.overlay.remove(); this.overlay = null; }
        $(window).off('resize.popup');
        this.isOpen = false;
    }
};

使用示例

<!-- HTML -->
<button id="btnOpen">打開彈層</button>
<div id="popupBox" class="popup-box" style="display:none;width:400px;height:300px;background:#fff;position:absolute;border:1px solid #ddd;padding:20px;">
    <h3>彈層標題</h3>
    <p>內容區域...</p>
    <button id="btnClose">關閉</button>
</div>

<script>
var popup = new PopupLayer({
    trigger: '#btnOpen',
    popupBlk: '#popupBox',
    closeBtn: '#btnClose',
    useOverlay: true,
    useFx: true,
    offsets: { x: 0, y: -41 } // 向上偏移 41px
});</script>

擴展:拖拽移動功能

// 在 init 中添加
if (this.settings.draggable) {
    var $titleBar = this.popupLayer.find('.popup-title');
    $titleBar.css('cursor', 'move').on('mousedown', function(e) {
        var offsetX = e.pageX - self.popupLayer.offset().left;
        var offsetY = e.pageY - self.popupLayer.offset().top;
        $(document).on('mousemove.drag', function(e) {
            self.popupLayer.css({
                left: e.pageX - offsetX,
                top: e.pageY - offsetY
            });
        });
        $(document).on('mouseup.drag', function() {
            $(document).off('mousemove.drag mouseup.drag');
        });
    });
}

插件化封裝($.fn.popupLayer)

$.fn.popupLayer = function(options) {
    return this.each(function() {
        var $trigger = $(this);
        var opts = $.extend({}, options, { trigger: $trigger });
        var instance = new PopupLayer(opts);
        $trigger.data('popupLayer', instance);
    });
};

// 使用
$('#btnOpen').popupLayer({
    popupBlk: '#popupBox',
    closeBtn: '#btnClose',
    useOverlay: true,
    useFx: true
});

現代化遷移建議

  • 使用 <dialog> 元素替代手動遮罩/定位。
  • 用 CSS Transition/Animation 替代 jQuery animate,性能更好。
  • 採用 position: fixed + transform: translate(-50%, -50%) 實現真正居中。
  • 組件庫選型:Bootstrap Modal、Element Plus Dialog、Ant Design Modal、SweetAlert2。

總結

彈出層核心要素:觸發器綁定、遮罩層管理、居中定位、動畫過渡、拖拽交互、銷毀清理。本文實現展示了經典 jQuery 組件開發模式:構造函數 + 原型方法 + 選項合併 + 事件代理 + 實例緩存。現代項目建議直接使用成熟組件庫,專注業務邏輯而非輪子製造。

copyright © 萬盛學電腦網 all rights reserved