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

离线验证 Foundation 5 麦哲伦吸顶切换、Top Bar 集成、内边距重置与 data-options

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-magellan.py
explore-magellan.py299 行
"""Offline Playwright Chromium lab for Foundation Ch 22 (magellan)."""
import json
from playwright.sync_api import sync_playwright

FOUNDATION_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; padding: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; color: #222; }
[data-magellan-expedition], [data-magellan-expedition-clone] {
  background: #ffffff;
  z-index: 50;
  min-width: 100%;
  padding: 10px;
}
[data-magellan-expedition].is-fixed {
  position: fixed;
  left: 0;
  right: 0;
}
.sub-nav { display: flex; gap: 16px; margin: 0; padding: 0; }
.sub-nav dd { margin: 0; }
.sub-nav dd a { display: inline-block; padding: 4px 12px; color: #999999; text-decoration: none; border-radius: 3px; }
.sub-nav dd.active a, .sub-nav dd.current a { background: #008cba; color: #ffffff; font-weight: 700; }
.top-bar { background: #333333; height: 45px; line-height: 45px; padding: 0 12px; }
.top-bar ul.left { list-style: none; margin: 0; padding: 0; display: flex; }
.top-bar ul.left li a { display: block; padding: 0 15px; color: #ffffff; text-decoration: none; }
.top-bar ul.left li.active a { background: #008cba; }
.spacer { height: 150px; background: #f4f4f4; }
.section-block { height: 420px; padding: 16px; border-top: 1px solid #ddd; }
"""

MAGELLAN_JS = """
function parseOptions(str) {
  const opts = { active_class: 'active', threshold: 0, destination_threshold: 20, fixed_top: 0 };
  if (!str) return opts;
  str.split(';').forEach(pair => {
    const parts = pair.split(':');
    if (parts.length === 2) {
      const k = parts[0].trim();
      const v = parts[1].trim();
      if (k === 'active_class') opts[k] = v;
      else if (k in opts) opts[k] = Number(v);
    }
  });
  return opts;
}

function initMagellan(scope) {
  const exp = scope.querySelector('[data-magellan-expedition]');
  const opts = parseOptions(exp.getAttribute('data-options'));
  const originTop = exp.getBoundingClientRect().top + window.scrollY;
  const arrivals = Array.from(exp.querySelectorAll('[data-magellan-arrival]'));
  const dests = Array.from(scope.querySelectorAll('[data-magellan-destination]'));

  function update() {
    const y = window.scrollY;
    const fixAt = opts.threshold > 0 ? opts.threshold : originTop;
    if (y >= fixAt) {
      exp.classList.add('is-fixed');
      exp.style.top = opts.fixed_top + 'px';
    } else {
      exp.classList.remove('is-fixed');
      exp.style.top = '';
    }
    let currentKey = null;
    for (const d of dests) {
      const top = d.getBoundingClientRect().top + window.scrollY;
      if (y + opts.destination_threshold >= top) {
        currentKey = d.getAttribute('data-magellan-destination');
      }
    }
    arrivals.forEach(a => {
      const match = currentKey !== null && a.getAttribute('data-magellan-arrival') === currentKey;
      a.classList.toggle(opts.active_class, match);
    });
  }
  window.addEventListener('scroll', update);
  window._magellanUpdate = update;
  update();
}
"""

SUBNAV_HTML = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
  <div class="spacer">Header Spacer</div>
  <div id="exp" data-magellan-expedition="fixed">
    <dl class="sub-nav">
      <dd id="arr1" data-magellan-arrival="page1"><a href="#page1">Page 1</a></dd>
      <dd id="arr2" data-magellan-arrival="page2"><a href="#page2">Page 2</a></dd>
    </dl>
  </div>
  <div data-magellan-expedition-clone id="clone" style="display:none;"></div>
  <div class="section-block">
    <h3 id="d1" data-magellan-destination="page1">Page1</h3>
    <a name="page1"></a>
    <p>第一部分内容</p>
  </div>
  <div class="section-block">
    <h3 id="d2" data-magellan-destination="page2">Page2</h3>
    <a name="page2"></a>
    <p>第二部分内容</p>
  </div>
  <div class="section-block">底部延伸区</div>
  <script>{MAGELLAN_JS} initMagellan(document);</script>
</body>
</html>
"""

TOPBAR_HTML = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
  <div class="spacer">Header Spacer</div>
  <div id="exp" data-magellan-expedition="fixed">
    <nav class="top-bar" data-topbar>
      <section class="top-bar-section">
        <ul class="left">
          <li id="li1" data-magellan-arrival="page1"><a href="#page1">Page 1</a></li>
          <li id="li2" data-magellan-arrival="page2"><a href="#page2">Page 2</a></li>
        </ul>
      </section>
    </nav>
  </div>
  <div class="section-block"><h3 id="d1" data-magellan-destination="page1">Page1</h3><a name="page1"></a></div>
  <div class="section-block"><h3 id="d2" data-magellan-destination="page2">Page2</h3><a name="page2"></a></div>
  <div class="section-block">底部延伸区</div>
  <script>{MAGELLAN_JS} initMagellan(document);</script>
</body>
</html>
"""

OPTIONS_HTML = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
  <div class="spacer">Header Spacer</div>
  <div id="exp" data-magellan-expedition="fixed" data-options="active_class:current; threshold:120; destination_threshold:60; fixed_top:24">
    <dl class="sub-nav">
      <dd id="arr1" data-magellan-arrival="page1"><a href="#page1">Page 1</a></dd>
      <dd id="arr2" data-magellan-arrival="page2"><a href="#page2">Page 2</a></dd>
    </dl>
  </div>
  <div class="section-block"><h3 id="d1" data-magellan-destination="page1">Page1</h3><a name="page1"></a></div>
  <div class="section-block"><h3 id="d2" data-magellan-destination="page2">Page2</h3><a name="page2"></a></div>
  <div class="section-block">底部延伸区</div>
  <script>{MAGELLAN_JS} initMagellan(document);</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(viewport={"width": 800, "height": 500})

        # Case 1: basic sub-nav expedition fixed & scroll spy
        page.set_content(SUBNAV_HTML)
        r1 = page.evaluate("""() => {
            const exp = document.getElementById('exp');
            const arr1 = document.getElementById('arr1');
            const arr2 = document.getElementById('arr2');
            const initPos = getComputedStyle(exp).position;
            const d1Top = Math.round(document.getElementById('d1').getBoundingClientRect().top + window.scrollY);
            const d2Top = Math.round(document.getElementById('d2').getBoundingClientRect().top + window.scrollY);
            window.scrollTo(0, d1Top);
            window._magellanUpdate();
            const at1 = {
                position: getComputedStyle(exp).position,
                top: getComputedStyle(exp).top,
                arr1_active: arr1.classList.contains('active'),
                arr2_active: arr2.classList.contains('active'),
                arr1_bg: getComputedStyle(arr1.querySelector('a')).backgroundColor,
            };
            window.scrollTo(0, d2Top);
            window._magellanUpdate();
            const at2 = {
                arr1_active: arr1.classList.contains('active'),
                arr2_active: arr2.classList.contains('active'),
                arr2_bg: getComputedStyle(arr2.querySelector('a')).backgroundColor,
            };
            return { init_position: initPos, at_page1: at1, at_page2: at2 };
        }""")
        exp1 = {
            "init_position": "static",
            "at_page1": {
                "position": "fixed",
                "top": "0px",
                "arr1_active": True,
                "arr2_active": False,
                "arr1_bg": "rgb(0, 140, 186)",
            },
            "at_page2": {
                "arr1_active": False,
                "arr2_active": True,
                "arr2_bg": "rgb(0, 140, 186)",
            },
        }
        cases.append(dict(name="magellan_fixed_expedition_and_scroll_spy", passed=(r1 == exp1), expected=exp1, actual=r1))

        # Case 2: padding default 10px vs CSS override to 0px
        r2 = page.evaluate("""() => {
            const exp = document.getElementById('exp');
            const clone = document.getElementById('clone');
            const before = getComputedStyle(exp).paddingTop;
            const style = document.createElement('style');
            style.textContent = '[data-magellan-expedition], [data-magellan-expedition-clone] { padding: 0; }';
            document.head.appendChild(style);
            return {
                default_padding: before,
                after_override_exp: getComputedStyle(exp).paddingTop,
                after_override_clone: getComputedStyle(clone).paddingTop,
            };
        }""")
        exp2 = {
            "default_padding": "10px",
            "after_override_exp": "0px",
            "after_override_clone": "0px",
        }
        cases.append(dict(name="magellan_padding_override", passed=(r2 == exp2), expected=exp2, actual=r2))

        # Case 3: top-bar integration
        page.set_content(TOPBAR_HTML)
        r3 = page.evaluate("""() => {
            const li1 = document.getElementById('li1');
            const li2 = document.getElementById('li2');
            const d2Top = Math.round(document.getElementById('d2').getBoundingClientRect().top + window.scrollY);
            window.scrollTo(0, d2Top);
            window._magellanUpdate();
            return {
                topbar_bg: getComputedStyle(document.querySelector('.top-bar')).backgroundColor,
                li1_active: li1.classList.contains('active'),
                li2_active: li2.classList.contains('active'),
                li2_link_bg: getComputedStyle(li2.querySelector('a')).backgroundColor,
            };
        }""")
        exp3 = {
            "topbar_bg": "rgb(51, 51, 51)",
            "li1_active": False,
            "li2_active": True,
            "li2_link_bg": "rgb(0, 140, 186)",
        }
        cases.append(dict(name="magellan_topbar_integration", passed=(r3 == exp3), expected=exp3, actual=r3))

        # Case 4: data-options (active_class, threshold, destination_threshold, fixed_top)
        page.set_content(OPTIONS_HTML)
        r4 = page.evaluate("""() => {
            const exp = document.getElementById('exp');
            const arr1 = document.getElementById('arr1');
            const arr2 = document.getElementById('arr2');
            const d2Top = Math.round(document.getElementById('d2').getBoundingClientRect().top + window.scrollY);
            window.scrollTo(0, 100);
            window._magellanUpdate();
            const beforeThreshold = exp.classList.contains('is-fixed');
            window.scrollTo(0, 125);
            window._magellanUpdate();
            const afterThreshold = {
                fixed: exp.classList.contains('is-fixed'),
                fixed_top: getComputedStyle(exp).top,
            };
            // Scroll to 50px before d2Top: destination_threshold=60 triggers page2 early
            window.scrollTo(0, d2Top - 50);
            window._magellanUpdate();
            return {
                fixed_at_100: beforeThreshold,
                fixed_at_125: afterThreshold.fixed,
                fixed_top_px: afterThreshold.fixed_top,
                arr2_has_current_early: arr2.classList.contains('current'),
                arr2_has_default_active: arr2.classList.contains('active'),
                arr1_has_current: arr1.classList.contains('current'),
            };
        }""")
        exp4 = {
            "fixed_at_100": False,
            "fixed_at_125": True,
            "fixed_top_px": "24px",
            "arr2_has_current_early": True,
            "arr2_has_default_active": False,
            "arr1_has_current": False,
        }
        cases.append(dict(name="magellan_data_options_behavior", passed=(r4 == exp4), expected=exp4, actual=r4))

        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/foundation-magellan-lab/explore-magellan.py

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

下载课程关联工程包:Foundation

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

下载课程关联工程包:Foundation

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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