萬盛學電腦網

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

原生 JavaScript 實現可拖拽彈窗輸入框:遮罩、居中、iframe 隔離完整代碼

功能特性

  • 🎯 模態遮罩層 (可配置顏色/透明度)
  • 🖱️ 標題欄拖拽移動 (邊界限制)
  • 📐 自動居中 + 窗口 resize 跟隨
  • 📝 內嵌輸入框表單
  • 🔧 回調函數支持 (確認/取消)
  • 🌐 IE6+ 兼容 (含 iframe 遮罩 select 穿透)

核心實現 (精簡版)

function AlertWin(options) {
    this.config = $.extend({
        title: '提示',
        message: '',
        width: 350,
        height: 180,
        hasInput: false,
        inputPlaceholder: '',
        inputValue: '',
        confirmText: '確定',
        cancelText: '取消',
        onConfirm: null, // function(value, closeFn)
        onCancel: null,  // function(closeFn)
        showMask: true,
        maskOpacity: 0.3,
        draggable: true
    }, options);
    
    this._render();
    this._bindEvents();
    this._center();
}

AlertWin.prototype = {
    _render: function() {
        var c = this.config;
        var html = '';
        
        // 遮罩層
        if (c.showMask) {
            this.$mask = $('
').css({ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', background: '#000', opacity: c.maskOpacity, zIndex: 10000, display: 'none' }).appendTo('body'); // IE6 select 穿透修復 if ($.browser.msie && parseInt($.browser.version) < 7) { this.$mask.append(''); } } // 彈窗主體 this.$box = $('
').css({ position: 'fixed', zIndex: 10001, display: 'none', width: c.width, background: '#fff', border: '1px solid #666', boxShadow: '0 4px 12px rgba(0,0,0,0.3)' }).appendTo('body'); // 標題欄 this.$titleBar = $('
').css({ height: '30px', lineHeight: '30px', padding: '0 10px', background: '#666', color: '#fff', fontWeight: 'bold', cursor: c.draggable ? 'move' : 'default', borderBottom: '1px solid #999' }).text(c.title).appendTo(this.$box); // 關閉按鈕 $('×').css({ float: 'right', cursor: 'pointer', fontSize: '18px', lineHeight: '30px' }).appendTo(this.$titleBar); // 內容區 this.$content = $('
').css({ padding: '20px', textAlign: 'center' }).appendTo(this.$box); if (c.hasInput) { this.$input = $('').css({ width: '80%', padding: '8px', fontSize: '14px', border: '1px solid #ccc', borderRadius: '3px' }).val(c.inputValue).attr('placeholder', c.inputPlaceholder).appendTo(this.$content); } else { this.$content.text(c.message); } // 底部按鈕 var $btnWrap = $('
').css({ padding: '15px', textAlign: 'right', borderTop: '1px solid #eee' }).appendTo(this.$box); this.$btnCancel = $('

使用示例

// 1. 簡單提示
AlertWin.alert('操作成功!', function() { console.log('用戶點擊確定'); });

// 2. 確認框
AlertWin.confirm('確定要刪除嗎?', 
    function() { deleteItem(id); }, 
    function() { console.log('用戶取消'); }
);

// 3. 輸入框
AlertWin.prompt('請輸入姓名:', function(name) {
    if (name.trim()) saveName(name);
    else alert('姓名不能為空');
}, '默認值');

// 4. 完整配置
new AlertWin({
    title: '編輯用戶',
    hasInput: true,
    inputPlaceholder: '用戶名',
    inputValue: currentName,
    width: 400,
    onConfirm: function(name, close) {
        if (!name.trim()) { alert('不能為空'); return; }
        updateUser(id, name, function() { close(); });
    }
});

純 CSS 版 (無 JS 邏輯,僅展示/隱藏)

<style>
.modal-overlay {position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:1000;display:none;}
.modal-box {position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#fff;padding:20px;border-radius:4px;z-index:1001;min-width:300px;display:none;}
.modal-title {font-weight:bold;margin-bottom:15px;}
.modal-input {width:100%;padding:8px;margin:10px 0;border:1px solid #ddd;border-radius:3px;}
.modal-btns {text-align:right;}
.modal-btns button {margin-left:8px;padding:6px 16px;}
</style>

<div class="modal-overlay" id="overlay"></div>
<div class="modal-box" id="modal">
    <div class="modal-title">標題</div>
    <input class="modal-input" id="modalInput">
    <div class="modal-btns">
        <button onclick="closeModal()">取消</button>
        <button onclick="submitModal()">確定</button>
    </div>
</div>

避坑指南

  • ❌ position: fixed 在 transform 父元素中失效 → 彈窗直接掛在 body
  • ❌ IE6 select 穿透 → iframe 遮罩 hack (如上代碼)
  • ❌ 拖拽時文字被選中 → user-select: none / onselectstart="return false"
  • ✅ 離開頁面清理事件監聽器防內存洩漏
  • ✅ 多彈窗層級管理:維護 zIndex 計數器
copyright © 萬盛學電腦網 all rights reserved