萬盛學電腦網

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

jQuery UI Dialog 打造可拖曳、居中、動態插入內容的彈窗元件

基本用法:幾行代碼實現專業彈窗

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<div id="dialog-form" title="新增資料" style="display:none;">
    <form>
        <label>名稱:</label><input type="text" id="name"><br>
        <label>Email:</label><input type="email" id="email">
    </form>
</div>

<button id="openDialog">開啟彈窗</button>

<script>
$(function() {
    // 1. 初始化 Dialog,autoOpen: false 手動控制
    $('#dialog-form').dialog({
        autoOpen: false,
        modal: true,           // 模態遮罩
        draggable: true,       // 可拖曳
        resizable: false,      // 不可縮放
        width: 400,
        position: { my: 'center', at: 'center', of: window }, // 居中
        buttons: {
            '送出': function() {
                var data = { name: $('#name').val(), email: $('#email').val() };
                console.log('提交:', data);
                $(this).dialog('close');
            },
            '取消': function() { $(this).dialog('close'); }
        },
        close: function() { $('form', this).trigger('reset'); }
    });

    // 2. 觸發開啟
    $('#openDialog').click(function() {
        $('#dialog-form').dialog('open');
    });
});
</script>

進階:動態插入資料列 (appendTo 範例)

<button id="addRow">新增一列</button>
<table id="dataTable"><thead><tr><th>名稱</th><th>Email</th></tr></thead><tbody></tbody></table>

<script>
$('#addRow').click(function() {
    var name = $('#name').val();
    var email = $('#email').val();
    if (!name || !email) return alert('請填寫完整');

    // 建立 tr 並 appendTo tbody
    $('').append(
        $('').text(name),
        $('').text(email)
    ).appendTo('#dataTable tbody');

    // 可選:關閉彈窗並清空
    $('#dialog-form').dialog('close');
});
</script>

常用 Dialog 選項速查

選項說明常用值
autoOpen初始化時是否自動開啟false (手動控制)
modal是否模態 (背景遮罩、鎖定焦點)true
draggable標題列拖曳移動true
resizable右下角縮放手柄false (表單類通常固定尺寸)
width/height寬高 (px 或 'auto')400 / 'auto'
position定位方式{my:'center', at:'center', of:window}
show/hide開關動畫{effect:'fade', duration:300}
closeOnEscapeEsc 鍵關閉true
appendTo掛載容器'body' (預設)

動態載入內容 (AJAX)

$('#dialog-form').dialog({
    autoOpen: false,
    open: function() {
        var $dialog = $(this);
        $dialog.html('載入中...');
        $.get('/api/form/partial', function(html) {
            $dialog.html(html);
            // 重新綁定表單驗證等
        });
    }
});

無障礙 (Accessibility) 內建支援

  • 自動管理 aria-modal, role="dialog", aria-labelledby (標題 ID)。
  • 焦點陷阱:Tab 循環在彈窗內,Shift+Tab 反向,Esc 關閉。
  • 開啟時焦點移至第一個可聚焦元素;關閉時焦點回歸觸發按鈕。

現代替代方案

  • 原生 <dialog> 元素 (HTML5.2):dialog.showModal()、dialog.close()、::backdrop 樣式化。IE 不支援,需 Polyfill。
  • Headless UI Dialog (React/Vue):無樣式、完全可控、無障礙優先。
  • Radix UI Dialog、Ark UI Dialog:Headless 元件庫。
  • SweetAlert2、Swal:專注提示/確認類彈窗,API 簡潔。

總結

jQuery UI Dialog 提供開箱即用的模態彈窗、拖曳、居中、按鈕、動畫、無障礙支援。核心流程:autoOpen:false 初始化 → 事件觸發 dialog('open') → 內容可動態載入/操作 → dialog('close') 關閉。新專案建議遷移至原生 <dialog> 或 Headless 元件庫。

copyright © 萬盛學電腦網 all rights reserved