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

运行水平固定导航栏、data-offset 阈值、垂直胶囊导航与容器级滚动监听实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-scrollspy.py
explore-scrollspy.py238 行
"""Offline Playwright Chromium verification for Bootstrap 4 Chapter 31: Scrollspy."""
import json
import platform
from playwright.sync_api import sync_playwright

BS4_SCROLLSPY_CSS = """
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; font-family: Arial, sans-serif; }
body { position: relative; }
.navbar { display: flex; align-items: center; padding: 0 16px; height: 50px; }
.bg-dark { background-color: #343a40; }
.navbar-dark .nav-link { color: rgba(255,255,255,.5); text-decoration: none; padding: 8px 12px; display: block; }
.navbar-dark .nav-link.active { color: #ffffff; background-color: #007bff; border-radius: 4px; }
.fixed-top { position: fixed; top: 0; right: 0; left: 0; z-index: 1030; }
.navbar-nav { display: flex; list-style: none; margin: 0; padding: 0; gap: 8px; }
.container-fluid { width: 100%; padding: 0 15px; }
.row { display: flex; flex-wrap: wrap; margin: 0 -15px; }
.col-4 { flex: 0 0 33.333333%; max-width: 33.333333%; padding: 0 15px; }
.col-8 { flex: 0 0 66.666667%; max-width: 66.666667%; padding: 0 15px; }
@media (min-width: 576px) {
  .col-sm-3 { flex: 0 0 25%; max-width: 25%; }
  .col-sm-9 { flex: 0 0 75%; max-width: 75%; }
}
.nav { display: flex; flex-wrap: wrap; list-style: none; padding-left: 0; margin: 0; }
.flex-column { flex-direction: column; }
.nav-pills .nav-link { display: block; padding: 8px 16px; border-radius: 4px; color: #007bff; text-decoration: none; }
.nav-pills .nav-link.active { color: #ffffff; background-color: #007bff; }
#myScrollspy ul.nav-pills { position: fixed; top: 20px; width: 160px; }
.spy-section { height: 500px; padding-top: 60px; }
.spy-box { position: relative; height: 220px; overflow-y: auto; border: 1px solid #dee2e6; }
.spy-box-section { height: 220px; padding: 12px; }
"""

BS4_SCROLLSPY_JS = """
function initScrollspy(container) {
  const targetSel = container.getAttribute('data-target');
  const offset = parseInt(container.getAttribute('data-offset') || '10', 10);
  const targetEl = document.querySelector(targetSel);
  const isBody = container === document.body;
  const links = Array.from(targetEl.querySelectorAll('a.nav-link[href^="#"]'));
  const targets = links.map(link => {
    const href = link.getAttribute('href');
    const sec = document.querySelector(href);
    return { link, href, sec };
  }).filter(item => item.sec !== null);

  function refresh() {
    const scrollTop = isBody ? window.scrollY : container.scrollTop;
    const pos = scrollTop + offset;
    let activeItem = targets[0] || null;
    for (const item of targets) {
      const top = isBody ? item.sec.offsetTop : item.sec.offsetTop;
      if (pos >= top) {
        activeItem = item;
      }
    }
    for (const link of links) {
      link.classList.remove('active');
    }
    if (activeItem) {
      activeItem.link.classList.add('active');
    }
    return activeItem ? activeItem.href : null;
  }

  const scroller = isBody ? window : container;
  scroller.addEventListener('scroll', refresh);
  refresh();
  return refresh;
}
"""


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)
        try:
            page = browser.new_page(viewport={"width": 800, "height": 400})

            # Case 1: Horizontal fixed-top navbar scrollspy
            html1 = f"""<!doctype html><html><head><style>{BS4_SCROLLSPY_CSS}</style></head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
  <nav class="navbar bg-dark navbar-dark fixed-top">
    <ul class="navbar-nav">
      <li class="nav-item"><a class="nav-link" href="#section1">Section 1</a></li>
      <li class="nav-item"><a class="nav-link" href="#section2">Section 2</a></li>
      <li class="nav-item"><a class="nav-link" href="#section3">Section 3</a></li>
    </ul>
  </nav>
  <div id="section1" class="spy-section"><h1>Section 1</h1></div>
  <div id="section2" class="spy-section"><h1>Section 2</h1></div>
  <div id="section3" class="spy-section"><h1>Section 3</h1></div>
  <script>{BS4_SCROLLSPY_JS} window.__refresh = initScrollspy(document.body);</script>
</body></html>"""
            page.set_content(html1)
            body_pos = page.eval_on_selector("body", "el => getComputedStyle(el).position")
            nav_pos = page.eval_on_selector("nav.navbar", "el => getComputedStyle(el).position")
            active_at = {}
            for y in (0, 500, 1000):
                page.evaluate(f"window.scrollTo(0, {y}); window.__refresh();")
                active_at[str(y)] = page.eval_on_selector("a.nav-link.active", "el => el.getAttribute('href')")
            exp1 = {"body_position": "relative", "nav_position": "fixed", "active_by_scrollY": {"0": "#section1", "500": "#section2", "1000": "#section3"}}
            act1 = {"body_position": body_pos, "nav_position": nav_pos, "active_by_scrollY": active_at}
            cases.append(dict(
                name="horizontal_navbar_scrollspy",
                inputs=dict(data_spy="scroll", data_target=".navbar", data_offset=50, scroll_positions=[0, 500, 1000]),
                prerequisites="body 设置 position: relative 与 data-spy='scroll',fixed-top 导航栏高 50px,三个区块各高 500px",
                action="在离线 Chromium 中滚动窗口至 0、500、1000px 并读取高亮的 .nav-link.active 锚点。",
                expected=exp1,
                actual=act1,
                measurements=dict(section_tops=page.evaluate("[document.getElementById('section1').offsetTop, document.getElementById('section2').offsetTop, document.getElementById('section3').offsetTop]")),
                passed=(act1 == exp1),
            ))

            # Case 2: data-offset default 10px vs custom 50px threshold
            offset_results = {}
            for off in (10, 50):
                html2 = html1.replace('data-offset="50"', f'data-offset="{off}"')
                page.set_content(html2)
                page.evaluate("window.scrollTo(0, 460); window.__refresh();")
                offset_results[f"offset_{off}"] = page.eval_on_selector("a.nav-link.active", "el => el.getAttribute('href')")
            exp2 = {"offset_10": "#section1", "offset_50": "#section2"}
            cases.append(dict(
                name="scrollspy_offset_threshold",
                inputs=dict(scrollY=460, section2_top=500, offsets=[10, 50]),
                prerequisites="section2 顶部位于 500px,分别配置默认 data-offset='10' 与 data-offset='50'",
                action="将页面滚动至 460px,对比两种 data-offset 下是否提前激活 #section2。",
                expected=exp2,
                actual=offset_results,
                measurements=dict(effective_pos_10=470, effective_pos_50=510),
                passed=(offset_results == exp2),
            ))

            # Case 3: Vertical pills scrollspy
            html3 = f"""<!doctype html><html><head><style>{BS4_SCROLLSPY_CSS}</style></head>
<body data-spy="scroll" data-target="#myScrollspy" data-offset="1">
  <div class="container-fluid">
    <div class="row">
      <nav class="col-sm-3 col-4" id="myScrollspy">
        <ul class="nav nav-pills flex-column">
          <li class="nav-item"><a class="nav-link active" href="#section1">Section 1</a></li>
          <li class="nav-item"><a class="nav-link" href="#section2">Section 2</a></li>
          <li class="nav-item"><a class="nav-link" href="#section3">Section 3</a></li>
        </ul>
      </nav>
      <div class="col-sm-9 col-8" id="contentCol">
        <div id="section1" class="spy-section"><h1>Section 1</h1></div>
        <div id="section2" class="spy-section"><h1>Section 2</h1></div>
        <div id="section3" class="spy-section"><h1>Section 3</h1></div>
      </div>
    </div>
  </div>
  <script>{BS4_SCROLLSPY_JS} window.__refresh = initScrollspy(document.body);</script>
</body></html>"""
            page.set_content(html3)
            ul_dir = page.eval_on_selector("#myScrollspy ul.nav-pills", "el => getComputedStyle(el).flexDirection")
            nav_w = round(page.eval_on_selector("#myScrollspy", "el => el.getBoundingClientRect().width"))
            col_w = round(page.eval_on_selector("#contentCol", "el => el.getBoundingClientRect().width"))
            v_active = {}
            for y in (0, 500, 1000):
                page.evaluate(f"window.scrollTo(0, {y}); window.__refresh();")
                v_active[str(y)] = page.eval_on_selector("#myScrollspy a.nav-link.active", "el => el.getAttribute('href')")
            active_bg = page.eval_on_selector("#myScrollspy a.nav-link.active", "el => getComputedStyle(el).backgroundColor")
            exp3 = {
                "pills_flex_direction": "column",
                "nav_width_px": 200,
                "content_width_px": 600,
                "active_bg": "rgb(0, 123, 255)",
                "active_by_scrollY": {"0": "#section1", "500": "#section2", "1000": "#section3"},
            }
            act3 = {
                "pills_flex_direction": ul_dir,
                "nav_width_px": nav_w,
                "content_width_px": col_w,
                "active_bg": active_bg,
                "active_by_scrollY": v_active,
            }
            cases.append(dict(
                name="vertical_pills_scrollspy",
                inputs=dict(viewport_width=800, data_target="#myScrollspy", data_offset=1),
                prerequisites="左侧 nav.col-sm-3 使用 .nav.nav-pills.flex-column,右侧 .col-sm-9 承载三节内容",
                action="在 800px 视口验证左右 1:3 宽度分配、垂直方向及滚动切换 #section1/#section2/#section3 高亮状态。",
                expected=exp3,
                actual=act3,
                measurements=dict(ratio=round(col_w / nav_w, 2)),
                passed=(act3 == exp3),
            ))

            # Case 4: Container-level relative positioning & href/id matching validation
            html4 = f"""<!doctype html><html><head><style>{BS4_SCROLLSPY_CSS}</style></head>
<body>
  <nav id="boxNav" class="navbar bg-dark navbar-dark">
    <ul class="navbar-nav">
      <li class="nav-item"><a class="nav-link" href="#box1">Box 1</a></li>
      <li class="nav-item"><a class="nav-link" href="#box2">Box 2</a></li>
      <li class="nav-item"><a class="nav-link" href="#missing">Missing</a></li>
    </ul>
  </nav>
  <div id="scrollBox" class="spy-box" data-spy="scroll" data-target="#boxNav" data-offset="10">
    <div id="box1" class="spy-box-section">Box 1</div>
    <div id="box2" class="spy-box-section">Box 2</div>
  </div>
  <script>{BS4_SCROLLSPY_JS} window.__refreshBox = initScrollspy(document.getElementById('scrollBox'));</script>
</body></html>"""
            page.set_content(html4)
            box_pos = page.eval_on_selector("#scrollBox", "el => getComputedStyle(el).position")
            page.evaluate("const b = document.getElementById('scrollBox'); b.scrollTop = 215; window.__refreshBox();")
            box_active = page.eval_on_selector("#boxNav a.nav-link.active", "el => el.getAttribute('href')")
            missing_active = page.eval_on_selector("#boxNav a[href='#missing']", "el => el.classList.contains('active')")
            exp4 = {"container_position": "relative", "active_href": "#box2", "missing_link_active": False}
            act4 = {"container_position": box_pos, "active_href": box_active, "missing_link_active": missing_active}
            cases.append(dict(
                name="relative_position_and_id_matching",
                inputs=dict(container_scrollTop=215, data_offset=10, links=["#box1", "#box2", "#missing"]),
                prerequisites="独立滚动容器 #scrollBox 具备 position: relative 与 overflow-y: auto,导航含未匹配锚点 #missing",
                action="将容器滚至 215px,核对有效匹配锚点 #box2 激活而无对应元素的 #missing 保持未激活。",
                expected=exp4,
                actual=act4,
                measurements=dict(box2_offsetTop=page.eval_on_selector("#box2", "el => el.offsetTop")),
                passed=(act4 == exp4),
            ))
        finally:
            browser.close()

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/bootstrap4-scrollspy-lab/explore-scrollspy.py

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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