Foundation Magellan
核对 Foundation 5 麦哲伦(Magellan)吸顶滚动监听导航的标记映射、与 Top Bar 集成、默认 10px 内边距清除及四大 data-options 选项。
学完这一章,你能够
- 核对 Foundation 5 麦哲伦(Magellan)吸顶滚动监听导航的标记映射、与 Top Bar 集成、默认 10px 内边距清除及四大 data-options 选项。
麦哲伦(Magellan)滚动索引结构与解析
麦哲伦(Magellan)是 Foundation 5 提供的吸顶滚动监听导航组件:用户纵向滚动长页面时,导航栏自动固定在视口顶部,并依据当前阅读位置高亮对应章节入口。
搭建基本麦哲伦导航分四步:先在导航外层 `<div>` 添加 `data-magellan-expedition="fixed"`;接着在 `<dl class="sub-nav">` 内的 `<dd>`(或导航列表的 `<li>`)上声明 `data-magellan-arrival="value"` 并放置指向 `#value` 的锚点链接;然后在正文各章节标题上添加 `data-magellan-destination="value"` 且紧随 `<a name="value"></a>`,保持目标值与 `data-magellan-arrival` 完全一致(如 `page1`、`page2`);最后调用 `$(document).foundation();` 初始化脚本。本站离线 Chromium 实测显示:滚动至 `page1` 时容器由 `static` 切换为 `position: fixed; top: 0px`,对应项获 `.active` 且链接背景变为 `rgb(0, 140, 186)`;继续滚至 `page2` 后激活态自动切向 `page2`。
结合头部工具条(Top Bar)与清除默认内边距
麦哲伦容器除搭配 `.sub-nav` 外,也可直接包裹 `<nav class="top-bar" data-topbar>` 头部工具条,把 `data-magellan-arrival` 写在 `.top-bar-section > ul.left > li` 上。离线实测确认深灰顶栏(`rgb(51, 51, 51)`)滚动到 `page2` 时,`li[data-magellan-arrival="page2"]` 正确切换为 `.active` 并呈现蓝色高亮背景。
默认样式下,麦哲伦 `<div>` 及其占位克隆节点均带有 `10px` 内边距;如需与通栏顶栏无缝贴合,可通过规则 `[data-magellan-expedition], [data-magellan-expedition-clone] { padding: 0; }` 一并归零。实测覆盖前后计算内边距由 `10px` 降至 `0px`。
使用 data-options 定制麦哲伦选项
在 `[data-magellan-expedition="fixed"]` 容器上附加 `data-options`(例如 `data-options="destination_threshold:60"`)可精细控制吸顶时机、激活类名与偏移量。本站实测同时配置 `active_class:current; threshold:120; destination_threshold:60; fixed_top:24`:滚动至 `100px` 时保持非固定,超过 `125px` 后吸顶且 `top: 24px`;距 `page2` 顶部尚余 `50px` 时即提前激活并施加自定义类名 `current`(不添加默认 `active`)。全部四项选项见下表。
Foundation 5 麦哲伦导航 data-options 选项对照表
| 选项名 | 类型 | 默认值 | 作用与实测说明 |
| `active_class` | string | `active` | 指定滚动命中目标章节时添加到导航项的激活类名,实测设为 `current` 可替换默认 `active` |
| `threshold` | number | `0` | 触发导航固定定位的滚动像素阈值;默认 `0` 自动按元素原位置计算,实测设为 `120` 时在 `100px` 未固定、`125px` 固定 |
| `destination_threshold` | number | `20` | 目标章节进入视口顶部多少像素内即视为激活,实测设为 `60` 时距 `page2` 顶部 `50px` 即提前高亮 |
| `fixed_top` | number | `0` | 导航固定后距浏览器视口顶部的像素距离,实测设为 `24` 时计算样式 `top: 24px` |
离线验证 Foundation 5 麦哲伦吸顶切换、Top Bar 集成、内边距重置与 data-options
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
两者的值必须完全一致且与对应锚点链接的 href/#name 匹配,滚动监听才能准确高亮当前章节;清除默认内边距需同时对 [data-magellan-expedition] 和 [data-magellan-expedition-clone] 设置 padding: 0。