萬盛學電腦網

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

原生 JS 彈窗插件開發:拖拽、遮罩、多內容模式完整實現

功能特性

  • 🎯 支持 4 種內容模式:HTML 文本、圖片、DOM 節點、iframe
  • 🖱️ 標題欄拖拽移動
  • 🎭 遮罩層(可配置顏色/透明度)
  • 📐 自動居中 + 窗口 resize/scroll 跟隨
  • ⏱️ 可選自動關閉定時器
  • 🔧 回調函數擴展
  • 🌐 IE6+、Chrome、Firefox 兼容

配置選項總覽

var config = {
    targetCls: '.clickElem',      // 觸發元素選擇器
    title: '彈窗標題',            // 標題文本
    content: 'text:<p>內容</p>',  // 內容:text: | img: | id: | iframe:
    width: 400,                   // 內容寬度
    height: 300,                  // 內容高度
    theight: 30,                  // 標題高度
    drag: true,                   // 是否可拖拽
    time: 3000,                   // 自動關閉毫秒數(undefined 不關閉)
    showBg: true,                 // 顯示遮罩
    closable: '#window-close',    // 關閉按鈕選擇器
    bgColor: '#000',              // 遮罩顏色
    opacity: 0.5,                 // 遮罩透明度
    position: {x: 0, y: 0},       // 偏移(0,0 為居中)
    zIndex: 10000,                // 層級
    isScroll: true,               // 跟隨滾動
    isResize: true,               // 跟隨縮放
    callback: null                // 顯示後回調
};

核心類結構

function Overlay(options) {
    this.config = $.extend({}, this.defaultConfig, options);
    this.cache = { isRender: false, isShow: false, movable: false };
    this.init();
}

Overlay.prototype = {
    constructor: Overlay,
    
    init: function() {
        var self = this, cfg = self.config;
        $(cfg.targetCls).each(function() {
            $(this).off('click').on('click', function() {
                self._renderHTML();
                self._bindDrag();
            });
        });
        self._bindResize();
        self._bindScroll();
    },
    
    // 渲染彈窗 HTML(僅首次)
    _renderHTML: function() {
        if (this.cache.isRender) return;
        // 構建遮罩 + 彈窗容器 + 標題欄 + 內容區 + 關閉按鈕
        // 根據 content 類型填充內容
        this.cache.isRender = true;
    },
    
    // 拖拽邏輯
    _bindDrag: function() {
        var self = this, $title = $('#window-title');
        $title.on('mousedown', function(e) {
            if (!self.config.drag) return;
            var startX = e.clientX, startY = e.clientY;
            var left = parseInt($('#window-box').css('left'));
            var top = parseInt($('#window-box').css('top'));
            
            $(document).on('mousemove.drag', function(e) {
                $('#window-box').css({
                    left: left + e.clientX - startX,
                    top: top + e.clientY - startY
                });
            }).on('mouseup.drag', function() {
                $(document).off('.drag');
            });
        });
    },
    
    // 窗口縮放跟隨居中
    _bindResize: function() {
        var self = this;
        $(window).on('resize', function() {
            if (self.cache.isShow) self._center();
        });
    },
    
    // 滾動跟隨
    _bindScroll: function() {
        var self = this;
        $(window).on('scroll', function() {
            if (self.cache.isShow && self.config.isScroll) self._center();
        });
    },
    
    _center: function() {
        var $box = $('#window-box'), cfg = this.config;
        $box.css({
            left: ($(window).width() - $box.outerWidth()) / 2 + cfg.position.x,
            top: ($(window).height() - $box.outerHeight()) / 2 + cfg.position.y
        });
    }
};

內容解析邏輯

_parseContent: function(str) {
    // text:HTML字符串
    if (str.indexOf('text:') === 0) return str.slice(5);
    // img:圖片鏈接
    if (str.indexOf('img:') === 0) return '<img src="' + str.slice(4) + '" />';
    // id:DOM節點ID
    if (str.indexOf('id:') === 0) return $('#' + str.slice(3)).html();
    // iframe:鏈接
    if (str.indexOf('iframe:') === 0) 
        return '<iframe src="' + str.slice(7) + '" frameborder="0" style="width:100%;height:100%"></iframe>';
    return str;
}

使用示例

// 1. 文字內容
new Overlay({
    targetCls: '.btn-text',
    content: 'text:<h3>歡迎使用</h3><p>這是文本內容</p>'
});

// 2. 圖片預覽
new Overlay({
    targetCls: '.btn-img',
    content: 'img:https://example.com/photo.jpg',
    width: 600, height: 400
});

// 3. 頁面內隱藏節點
new Overlay({
    targetCls: '.btn-dom',
    content: 'id:hiddenForm'
});

// 4. 嵌入外部頁面
new Overlay({
    targetCls: '.btn-iframe',
    content: 'iframe:https://example.com',
    width: 800, height: 600
});

CSS 樣式要點

#window-box {border: 5px solid #E9F3FD; background: #FFF; position: absolute;}
.window-title {height: 30px; background: #f0f0f0; cursor: move; position: relative;}
#window-close {position: absolute; right: 10px; top: 5px; width: 16px; height: 16px; 
               background: url(close.png) no-repeat; cursor: pointer;}
#window-content {padding: 10px; overflow: auto;}

此插件結構清晰、易擴展,可作為學習原生組件開發的參考範本。

copyright © 萬盛學電腦網 all rights reserved