蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery EasyUI 教程目录 68章
课程介绍
jQuery EasyUI / LEARN BY DOING

jEasyUI 创建对话框

核对 Dialog 作为特殊 Window 的顶部工具栏、主体内容与底部按钮栏标准四段结构,以及 resizable 默认禁止缩放与开启缩放的实测差异。

学完这一章,你能够

  • 核对 Dialog 作为特殊 Window 的顶部工具栏、主体内容与底部按钮栏标准四段结构,以及 resizable 默认禁止缩放与开启缩放的实测差异。

Dialog 组件定位与基础 DIV 声明

对话框(Dialog)是继承自 Window 的专用交互窗口,核心特点是原生提供位于主体上方的工具栏(toolbar)与位于底部的操作按钮区(buttons)。默认情况下对话框不允许拖拽改变大小(`resizable: false`),需要缩放时可显式设置 `resizable="true"`。

通过 `<div id="dd" class="easyui-dialog" title="My Dialog" iconCls="icon-ok" toolbar="#dlg-toolbar" buttons="#dlg-buttons">` 即可从标记直接创建标准对话框,并以选择器指向外部定义的工具栏与按钮容器。

工具栏、按钮区标准配置与缩放实测

配套的 `#dlg-toolbar` 通常放置 `plain="true"` 扁平风格链接按钮(如 `Add`、`Save`),而 `#dlg-buttons` 放置确认与关闭按钮(`Ok` 与调用 `$('#dd').dialog('close')` 的 `Cancel`),共同构成标题、工具栏、内容区、按钮栏四段标准结构。本站离线无头浏览器实测:挂载后 `#dlg-toolbar` 与 `#dlg-buttons` 均移入对话框容器内且纵坐标严格满足 `header < toolbar < body < buttons`;依次点击 `Add`、`Save`、`Ok` 记录 `['Add', 'Save', 'Ok']`,点击 `Cancel` 隐藏对话框;默认对话框 `resizable=false` 无缩放手柄且禁止调整(宽度锁定 `400px`),而配置 `resizable="true"` 的对话框带缩放手柄并可调整为 `480x260`。

来源示例压缩包 `jeasyui-win-dlg1.zip` 未联网下载,已通过上述无头浏览器实验核验标准四段装配、按钮关闭与缩放开关行为。

运行 EasyUI Dialog 四段结构装配、按钮关闭与 resizable 开关离线实验

含完整源码 · 228 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 49: Create Dialog."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI Dialog Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; font-size: 13px; }
  .dialog-wrap { border: 1px solid #95b8e7; background: #e0ecff; padding: 4px; box-sizing: border-box; margin-bottom: 14px; }
  .dialog-wrap.closed { display: none; }
  .dialog-header { padding: 4px 6px; font-weight: bold; }
  .dialog-toolbar { background: #f4f4f4; border: 1px solid #95b8e7; border-bottom: 0; padding: 4px 6px; }
  .dialog-body { background: #fff; border: 1px solid #95b8e7; box-sizing: border-box; }
  .dialog-button { background: #f4f4f4; border: 1px solid #95b8e7; border-top: 0; padding: 5px 6px; text-align: right; }
  .l-btn { display: inline-block; padding: 2px 8px; border: 1px solid #bbb; background: #fff; text-decoration: none; color: #333; margin-left: 4px; }
  .l-btn.plain { border-color: transparent; background: transparent; }
  .resize-handle { height: 6px; cursor: nwse-resize; background: #cfe0f5; }
</style>
</head>
<body>
<div id="dd" class="easyui-dialog" style="padding:5px;width:400px;height:200px;"
     title="My Dialog" iconCls="icon-ok" toolbar="#dlg-toolbar" buttons="#dlg-buttons">
  Dialog Content.
</div>
<div id="dlg-toolbar">
  <a href="#" id="tb-add" class="easyui-linkbutton" iconCls="icon-add" plain="true">Add</a>
  <a href="#" id="tb-save" class="easyui-linkbutton" iconCls="icon-save" plain="true">Save</a>
</div>
<div id="dlg-buttons">
  <a href="#" id="bt-ok" class="easyui-linkbutton" iconCls="icon-ok">Ok</a>
  <a href="#" id="bt-cancel" class="easyui-linkbutton" iconCls="icon-cancel">Cancel</a>
</div>

<div id="dd-resize" class="easyui-dialog" style="padding:5px;width:400px;height:200px;"
     title="Resizable Dialog" resizable="true">
  Resizable Body.
</div>

<script>
const actionLog = [];
const dialogs = new Map();

function initDialogs() {
  document.querySelectorAll(".easyui-dialog").forEach(el => {
    const title = el.getAttribute("title") || "";
    const iconCls = el.getAttribute("iconCls") || "";
    const tbSel = el.getAttribute("toolbar");
    const btSel = el.getAttribute("buttons");
    const resizable = el.getAttribute("resizable") === "true";
    const width = el.style.width || "400px";
    const height = el.style.height || "200px";
    const pad = el.style.padding || "0px";

    const wrap = document.createElement("div");
    wrap.className = "dialog-wrap";
    wrap.dataset.for = el.id;
    wrap.style.width = width;

    const header = document.createElement("div");
    header.className = "dialog-header";
    header.dataset.iconCls = iconCls;
    header.textContent = title;

    el.parentNode.insertBefore(wrap, el);
    wrap.appendChild(header);

    let tbEl = null;
    if (tbSel) {
      tbEl = document.querySelector(tbSel);
      if (tbEl) {
        tbEl.classList.add("dialog-toolbar");
        wrap.appendChild(tbEl);
      }
    }

    el.classList.add("dialog-body");
    el.style.width = "100%";
    el.style.height = height;
    el.style.padding = pad;
    wrap.appendChild(el);

    let btEl = null;
    if (btSel) {
      btEl = document.querySelector(btSel);
      if (btEl) {
        btEl.classList.add("dialog-button");
        wrap.appendChild(btEl);
      }
    }

    let handle = null;
    if (resizable) {
      handle = document.createElement("div");
      handle.className = "resize-handle";
      wrap.appendChild(handle);
    }

    dialogs.set(el.id, {
      resizable,
      wrap,
      header,
      tbEl,
      body: el,
      btEl,
      handle,
      close() { wrap.classList.add("closed"); },
      open() { wrap.classList.remove("closed"); },
      resize(w, h) {
        if (!resizable) return false;
        wrap.style.width = w + "px";
        el.style.height = h + "px";
        return true;
      }
    });
  });

  document.querySelectorAll("a.easyui-linkbutton").forEach(a => {
    a.classList.add("l-btn");
    if (a.getAttribute("plain") === "true") a.classList.add("plain");
  });
}

initDialogs();

document.getElementById("tb-add").addEventListener("click", (e) => { e.preventDefault(); actionLog.push("Add"); });
document.getElementById("tb-save").addEventListener("click", (e) => { e.preventDefault(); actionLog.push("Save"); });
document.getElementById("bt-ok").addEventListener("click", (e) => { e.preventDefault(); actionLog.push("Ok"); });
document.getElementById("bt-cancel").addEventListener("click", (e) => { e.preventDefault(); dialogs.get("dd").close(); });

window.lab = { dialogs, actionLog };
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML_DOC)

        # Case 1: Standard dialog anatomy: header < toolbar < body < buttons
        res1 = page.evaluate("""() => {
            const d = window.lab.dialogs.get("dd");
            const hTop = d.header.getBoundingClientRect().top;
            const tbTop = d.tbEl.getBoundingClientRect().top;
            const bTop = d.body.getBoundingClientRect().top;
            const btTop = d.btEl.getBoundingClientRect().top;
            return {
                title: d.header.textContent,
                iconCls: d.header.dataset.iconCls,
                bodyText: d.body.textContent.trim(),
                toolbarInsideDialog: d.wrap.contains(d.tbEl),
                buttonsInsideDialog: d.wrap.contains(d.btEl),
                strictTopOrder: (hTop < tbTop) && (tbTop < bTop) && (bTop < btTop)
            };
        }""")
        exp1 = {
            "title": "My Dialog",
            "iconCls": "icon-ok",
            "bodyText": "Dialog Content.",
            "toolbarInsideDialog": True,
            "buttonsInsideDialog": True,
            "strictTopOrder": True,
        }
        cases.append(dict(name="dialog_standard_anatomy_and_selector_mount", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Toolbar & button actions fire and Cancel closes dialog
        page.click("#tb-add")
        page.click("#tb-save")
        page.click("#bt-ok")
        page.click("#bt-cancel")
        res2 = page.evaluate("""() => ({
            actionLog: window.lab.actionLog,
            dialogHiddenAfterCancel: getComputedStyle(window.lab.dialogs.get("dd").wrap).display === "none"
        })""")
        exp2 = {"actionLog": ["Add", "Save", "Ok"], "dialogHiddenAfterCancel": True}
        cases.append(dict(name="dialog_toolbar_and_button_actions", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Default resizable=false vs resizable=true
        res3 = page.evaluate("""() => {
            const d1 = window.lab.dialogs.get("dd");
            const d2 = window.lab.dialogs.get("dd-resize");
            d1.open();
            const d1Attempt = d1.resize(480, 260);
            const d2Attempt = d2.resize(480, 260);
            return {
                defaultResizable: d1.resizable,
                defaultHasHandle: d1.handle !== null,
                defaultResizeBlocked: !d1Attempt,
                defaultWidthStayed: Math.round(d1.wrap.getBoundingClientRect().width),
                resizableHasHandle: d2.handle !== null,
                resizableUpdated: d2Attempt,
                resizableNewWidth: Math.round(d2.wrap.getBoundingClientRect().width),
                resizableNewBodyHeight: Math.round(d2.body.getBoundingClientRect().height)
            };
        }""")
        exp3 = {
            "defaultResizable": False,
            "defaultHasHandle": False,
            "defaultResizeBlocked": True,
            "defaultWidthStayed": 400,
            "resizableHasHandle": True,
            "resizableUpdated": True,
            "resizableNewWidth": 480,
            "resizableNewBodyHeight": 260,
        }
        cases.append(dict(name="dialog_resizable_default_false_vs_true", expected=exp3, actual=res3, passed=(res3 == exp3)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 header<toolbar<body<buttons 纵向序、Add/Save/Ok 动作日志与 Cancel 关闭,以及 resizable 默认锁定 400px 对比开启后缩放至 480x260。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a964.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1024.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

一是 Dialog 原生支持在主体上方挂载 toolbar 工具栏并在底部挂载 buttons 按钮栏;二是 Dialog 默认 resizable 为 false 不可拖拽缩放,而普通 Window 默认允许调整大小。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习