蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery EasyUI · 本地阅读预览
教程 / 前端开发 / jQuery EasyUI

jEasyUI 创建简单的菜单

使用 DIV 嵌套标记声明包含多级子菜单、图标项与分隔线的 Menu 组件,并调用 show/hide 控制定位显示。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

DIV 标记定义菜单结构与多级子项

jQuery EasyUI 的菜单(Menu)通过嵌套 `<div>` 标记声明:外层容器设置 `class="easyui-menu"` 与宽度(如 `width:120px`),内部每个直系 `<div>` 对应一项菜单命令,可绑定 `onclick` 事件或图标属性(如 `icon="icon-save"`);在某项内放置 `<span>Open</span>` 与嵌套 `<div style="width:150px;">` 即可生成二级子菜单(`Word`、`Excel`、`PowerPoint`);空元素 `<div class="menu-sep"></div>` 用于渲染水平分隔线。

通过 show 与 hide 方法控制菜单显隐

菜单组件初始化后默认处于隐藏状态,适合在右键上下文或按钮触发时调用 `$('#mm').menu('show', {left: 200, top: 100})` 在指定坐标弹出,并在需要时调用 `$('#mm').menu('hide')` 关闭。本站离线 Chromium 实测:`#mm` 初始 `display` 为 `none`,调用 `show(200, 100)` 后在 `(200, 100)` 显现,包含 `4` 个顶层菜单项、`1` 条分隔线与 `Save` 的 `icon-save` 属性;鼠标悬停 `Open` 展开含 `['Word', 'Excel', 'PowerPoint']` 的子菜单,点击 `New` 触发回调记录 `'new'`;调用 `hide` 后隐藏,再次 `show(60, 40)` 可准确重定位至 `(60, 40)`。原下载包 `jeasyui-mb-menu.zip` 未联网获取,已由本节离线实验验证。

离线 Chromium 实测 Menu 显隐坐标定位、二级子菜单展开与事件触发

python · 阅读源码
"""Offline Playwright Chromium verification lab for jEasyUI Simple Menu (Ch10)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jEasyUI Simple Menu Lab</title>
<style>
  body { margin: 0; font-family: Arial, sans-serif; }
  .easyui-menu { position: absolute; border: 1px solid #95b8e7; background: #fafafa; padding: 2px 0; display: none; box-sizing: border-box; }
  .menu-item { padding: 4px 10px; cursor: pointer; position: relative; font-size: 13px; }
  .menu-item:hover { background: #ffe48d; }
  .menu-sep { height: 1px; background: #ccc; margin: 3px 0; }
  .submenu { position: absolute; left: 100%; top: 0; border: 1px solid #95b8e7; background: #fafafa; display: none; }
</style>
</head>
<body>
  <div id="mm" class="easyui-menu" style="width:120px;">
    <div id="item-new" onclick="window.__log.push('new')">New</div>
    <div id="item-open">
      <span>Open</span>
      <div id="sub-open" style="width:150px;">
        <div><b>Word</b></div>
        <div>Excel</div>
        <div>PowerPoint</div>
      </div>
    </div>
    <div id="item-save" icon="icon-save">Save</div>
    <div class="menu-sep"></div>
    <div id="item-exit">Exit</div>
  </div>
  <script>
    window.__log = [];
    // Parse menu DOM structure
    (function initMenu(menuEl) {
      Array.from(menuEl.children).forEach(child => {
        if (child.classList.contains('menu-sep')) return;
        child.classList.add('menu-item');
        const sub = child.querySelector(':scope > div');
        if (sub) {
          sub.classList.add('submenu');
          child.addEventListener('mouseenter', () => { sub.style.display = 'block'; });
          child.addEventListener('mouseleave', () => { sub.style.display = 'none'; });
        }
      });
    })(document.getElementById('mm'));

    function $(sel) {
      const el = document.querySelector(sel);
      return {
        menu(method, opts) {
          if (method === 'show') {
            el.style.left = (opts.left || 0) + 'px';
            el.style.top = (opts.top || 0) + 'px';
            el.style.display = 'block';
          } else if (method === 'hide') {
            el.style.display = 'none';
          }
          return this;
        }
      };
    }
    window.$ = $;
  </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: Menu hidden on creation, then shown at left:200, top:100
        initially_hidden = page.evaluate("() => getComputedStyle(document.getElementById('mm')).display === 'none'")
        page.evaluate("() => $('#mm').menu('show', { left: 200, top: 100 })")
        act1 = page.evaluate("""(initHidden) => {
            const mm = document.getElementById('mm');
            const rect = mm.getBoundingClientRect();
            return {
                initiallyHidden: initHidden,
                visibleAfterShow: getComputedStyle(mm).display !== 'none',
                left: Math.round(rect.left),
                top: Math.round(rect.top),
                topLevelItems: mm.querySelectorAll(':scope > .menu-item').length,
                separatorCount: mm.querySelectorAll(':scope > .menu-sep').length,
                saveIconAttr: document.getElementById('item-save').getAttribute('icon')
            };
        }""", initially_hidden)
        exp1 = {
            "initiallyHidden": True,
            "visibleAfterShow": True,
            "left": 200,
            "top": 100,
            "topLevelItems": 4,
            "separatorCount": 1,
            "saveIconAttr": "icon-save",
        }
        cases.append({
            "name": "menu_initial_hidden_and_show_coords",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        })

        # Case 2: Hover Open to expand nested submenu & click New item
        page.hover("#item-open")
        sub_info = page.evaluate("""() => {
            const sub = document.getElementById('sub-open');
            return {
                submenuVisible: getComputedStyle(sub).display === 'block',
                submenuItems: Array.from(sub.children).map(el => el.textContent.trim())
            };
        }""")
        page.click("#item-new")
        clicked_log = page.evaluate("() => window.__log.slice()")
        act2 = dict(sub_info, clickedLog=clicked_log)
        exp2 = {
            "submenuVisible": True,
            "submenuItems": ["Word", "Excel", "PowerPoint"],
            "clickedLog": ["new"],
        }
        cases.append({
            "name": "submenu_hover_expand_and_item_click",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        })

        # Case 3: Hide menu then reposition via show(60, 40)
        page.evaluate("() => $('#mm').menu('hide')")
        hidden_now = page.evaluate("() => getComputedStyle(document.getElementById('mm')).display === 'none'")
        page.evaluate("() => $('#mm').menu('show', { left: 60, top: 40 })")
        rect3 = page.evaluate("""() => {
            const r = document.getElementById('mm').getBoundingClientRect();
            return { left: Math.round(r.left), top: Math.round(r.top) };
        }""")
        act3 = {"hiddenAfterHide": hidden_now, "repositionedLeft": rect3["left"], "repositionedTop": rect3["top"]}
        exp3 = {"hiddenAfterHide": True, "repositionedLeft": 60, "repositionedTop": 40}
        cases.append({
            "name": "menu_hide_method_and_context_reposition",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        })

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对菜单初始隐藏、show(200, 100) 精确定位与结构计数、悬停 Open 展示三级子项及点击 New 触发回调、hide 与重定位 (60, 40)。
离线 Chromium 实测 Menu 显隐坐标定位、二级子菜单展开与事件触发

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:02b52da94a8f12bf5981b99b3e209d54e9754b45ec10f6a9bf37ebf023ac9bae

下载本站示例源码

本地运行

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

下载jEasyUI 创建简单的菜单实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:1d1df10df8f4df631c4267cbbf6fcd5abec949b70ba21a609e42f1ebe706a370

常见错误与边界

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

练习与解答

在 EasyUI Menu 的 HTML 标记中,如何区分普通菜单项、带子菜单项与分隔线?

展开参考解答

普通项直接写为 <div>文本</div>;带子菜单的项内部放 <span>标题</span> 加一个子项容器 <div>;分隔线则使用带 class='menu-sep' 的空 <div>。

规范与官方依据