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

离线 Chromium 核验 Bootstrap 5 顶栏、嵌套垂直目录与列表组滚动监听

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-scrollspy.py
explore-scrollspy.py208 行
"""Offline Playwright Chromium verification for Bootstrap 5 Scrollspy (Ch 28)."""
import json
from playwright.sync_api import sync_playwright

BS5_SCROLLSPY_CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; }
.nav { display: flex; list-style: none; padding: 0; margin: 0; }
.flex-column { flex-direction: column; }
.nav-link { display: block; padding: 6px 12px; color: #0d6efd; text-decoration: none; border-radius: 4px; }
.nav-pills .nav-link.active { background-color: #0d6efd; color: #fff; }
.navbar { display: flex; padding: 8px 16px; background: #212529; }
.navbar .nav-link { color: rgba(255,255,255,0.65); }
.navbar .nav-link.active { color: #fff; font-weight: bold; }
.scroll-box { position: relative; height: 240px; overflow-y: auto; border: 1px solid #dee2e6; }
.section { height: 400px; padding: 16px; }
.list-group { display: flex; flex-direction: column; width: 200px; }
.list-group-item { padding: 8px 12px; border: 1px solid #dee2e6; text-decoration: none; color: #212529; }
.list-group-item.active { background: #0d6efd; color: #fff; border-color: #0d6efd; }
"""

BS5_SCROLLSPY_JS = """
function initScrollspy(container) {
  const targetSel = container.getAttribute('data-bs-target');
  const offset = Number(container.getAttribute('data-bs-offset') || 10);
  const targetNav = document.querySelector(targetSel);
  const links = Array.from(targetNav.querySelectorAll('a[href^="#"]'));
  const targets = links.map(a => ({
    link: a,
    el: container.querySelector(a.getAttribute('href')),
  })).filter(item => item.el);

  function refresh() {
    const pos = container.scrollTop + offset;
    let activeItem = targets[0];
    for (const item of targets) {
      if (item.el.offsetTop <= pos) {
        activeItem = item;
      }
    }
    links.forEach(a => a.classList.remove('active'));
    if (activeItem) {
      activeItem.link.classList.add('active');
      // Activate parent nav-link in nested .nav structure (BS5 scrollspy behavior)
      let parentNav = activeItem.link.closest('.nav');
      if (parentNav && parentNav.previousElementSibling && parentNav.previousElementSibling.classList.contains('nav-link')) {
        parentNav.previousElementSibling.classList.add('active');
      }
    }
  }
  container.addEventListener('scroll', refresh);
  refresh();
}
document.querySelectorAll('[data-bs-spy="scroll"]').forEach(initScrollspy);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_SCROLLSPY_CSS}</style></head>
<body>
  <nav id="topNav" class="navbar">
    <ul class="nav">
      <li><a class="nav-link" href="#section1">Section 1</a></li>
      <li><a class="nav-link" href="#section2">Section 2</a></li>
      <li><a class="nav-link" href="#section3">Section 3</a></li>
    </ul>
  </nav>
  <div id="spy-top" class="scroll-box" data-bs-spy="scroll" data-bs-target="#topNav" data-bs-offset="50" tabindex="0">
    <div id="section1" class="section"><h1>Section 1</h1></div>
    <div id="section2" class="section"><h1>Section 2</h1></div>
    <div id="section3" class="section"><h1>Section 3</h1></div>
  </div>

  <div style="display:flex;gap:16px;margin-top:16px;">
    <nav id="navbar-example3" class="nav nav-pills flex-column" style="width:180px;">
      <a class="nav-link" href="#item-1">Item 1</a>
      <nav class="nav nav-pills flex-column">
        <a class="nav-link" href="#item-1-1">Item 1-1</a>
        <a class="nav-link" href="#item-1-2">Item 1-2</a>
      </nav>
      <a class="nav-link" href="#item-2">Item 2</a>
      <a class="nav-link" href="#item-3">Item 3</a>
      <nav class="nav nav-pills flex-column">
        <a class="nav-link" href="#item-3-1">Item 3-1</a>
        <a class="nav-link" href="#item-3-2">Item 3-2</a>
      </nav>
    </nav>
    <div id="spy-nested" class="scroll-box" style="flex:1;" data-bs-spy="scroll" data-bs-target="#navbar-example3" data-bs-offset="0" tabindex="0">
      <div id="item-1" style="height:180px;">Item 1</div>
      <div id="item-1-1" style="height:180px;">Item 1-1</div>
      <div id="item-1-2" style="height:180px;">Item 1-2</div>
      <div id="item-2" style="height:180px;">Item 2</div>
      <div id="item-3" style="height:180px;">Item 3</div>
      <div id="item-3-1" style="height:180px;">Item 3-1</div>
      <div id="item-3-2" style="height:300px;">Item 3-2</div>
    </div>
  </div>

  <div style="display:flex;gap:16px;margin-top:16px;">
    <div id="list-example" class="list-group">
      <a class="list-group-item list-group-item-action" href="#list-item-1">Item 1</a>
      <a class="list-group-item list-group-item-action" href="#list-item-2">Item 2</a>
      <a class="list-group-item list-group-item-action" href="#list-item-3">Item 3</a>
      <a class="list-group-item list-group-item-action" href="#list-item-4">Item 4</a>
    </div>
    <div id="spy-list" class="scroll-box" style="flex:1;" data-bs-spy="scroll" data-bs-target="#list-example" data-bs-offset="0" tabindex="0">
      <div id="list-item-1" style="height:220px;">List 1</div>
      <div id="list-item-2" style="height:220px;">List 2</div>
      <div id="list-item-3" style="height:220px;">List 3</div>
      <div id="list-item-4" style="height:300px;">List 4</div>
    </div>
  </div>
<script>{BS5_SCROLLSPY_JS}</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": 900, "height": 900})
        page.set_content(HTML_DOC)

        # Case 1: top navbar scrollspy with offset=50
        c1_actual = page.evaluate("""() => {
            const box = document.querySelector('#spy-top');
            const out = { position: getComputedStyle(box).position };
            for (const y of [0, 360, 760]) {
                box.scrollTop = y;
                box.dispatchEvent(new Event('scroll'));
                out['at_' + y] = document.querySelector('#topNav .nav-link.active').getAttribute('href');
            }
            return out;
        }""")
        c1_expected = {
            "position": "relative",
            "at_0": "#section1",
            "at_360": "#section2",
            "at_760": "#section3",
        }
        cases.append({
            "name": "scrollspy_navbar_offset_activation",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: nested vertical nav-pills activating both parent and child
        c2_actual = page.evaluate("""() => {
            const box = document.querySelector('#spy-nested');
            const getActives = () => Array.from(document.querySelectorAll('#navbar-example3 .nav-link.active')).map(a => a.getAttribute('href'));
            box.scrollTop = 200;
            box.dispatchEvent(new Event('scroll'));
            const at_item_1_1 = getActives();
            box.scrollTop = 1090;
            box.dispatchEvent(new Event('scroll'));
            const at_item_3_2 = getActives();
            return { at_item_1_1, at_item_3_2 };
        }""")
        c2_expected = {
            "at_item_1_1": ["#item-1", "#item-1-1"],
            "at_item_3_2": ["#item-3", "#item-3-2"],
        }
        cases.append({
            "name": "scrollspy_nested_vertical_pills",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        })

        # Case 3: list-group scrollspy sequential transitions
        c3_actual = page.evaluate("""() => {
            const box = document.querySelector('#spy-list');
            const seq = [];
            for (const y of [0, 230, 450, 670]) {
                box.scrollTop = y;
                box.dispatchEvent(new Event('scroll'));
                seq.push(document.querySelector('#list-example .list-group-item.active').getAttribute('href'));
            }
            return { active_sequence: seq };
        }""")
        c3_expected = {
            "active_sequence": ["#list-item-1", "#list-item-2", "#list-item-3", "#list-item-4"],
        }
        cases.append({
            "name": "scrollspy_list_group_sync",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        })

        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/bootstrap5-scrollspy-lab/explore-scrollspy.py

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

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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