蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-mb-menu.py
explore-mb-menu.py166 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/jeasyui-mb-menu-lab/explore-mb-menu.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-mb-menu.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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