Foundation Joyride
核对 Foundation 5 Joyride 分步功能向导的 .joyride-list 定义、data-id 目标锚点映射、无 data-id 模态收尾步、data-button 定制及 JS 启动流程。
学完这一章,你能够
- 核对 Foundation 5 Joyride 分步功能向导的 .joyride-list 定义、data-id 目标锚点映射、无 data-id 模态收尾步、data-button 定制及 JS 启动流程。
创建分步功能向导(Joyride)
Joyride 是 Foundation 5 内置的 JavaScript 新手引导与功能巡览组件,可按顺序高亮页面上的关键区域并弹出气泡卡片。完整用法包含三部分:页面中带唯一 `id` 的目标元素(如 `<h3 id="first">` 与 `<h3 id="second">`)、定义各步骤内容的 `<ol class="joyride-list" data-joyride>` 列表,以及页面加载完成后的启动脚本。
步骤列表解析、模态步与启动脚本
在页面中先为每个引导站点元素设置唯一 `id`,再于 `<body>` 内(通常位于页面底部所有目标元素之后)使用 `<ol>` 或 `<ul>` 添加 `data-joyride` 属性与 `.joyride-list` 类;列表中每个 `<li>` 代表向导的一步,并通过 `data-id="value"` 与页面元素 `id` 一一对应(如 `data-id="first"` 锚定 `id="first"`),且 `<li>` 内部可自由编写 `<h4>`、`<p>` 等合法 HTML。本站离线 Chromium 实测确认:原始 `.joyride-list` 默认隐藏(`display: none`),启动后第 1 步气泡卡片(深灰背景 `rgb(51, 51, 51)`,默认按钮文案 `Next`)精准锚定于 `#first` 下方 `10px` 且左缘对齐;点击 `Next` 后第 1 步隐藏、第 2 步锚定于 `#second` 下方并正确渲染 `<h4>Second Stop</h4>`。
若某个 `<li>` 未设置 `data-id` 属性(例如用于欢迎页或结束说明),Joyride 不会锚定具体元素,而是以居中模态框叠加半透明背景的形式弹出;同时可用 `data-button="End"` 自定义底部按钮文案。向导需通过 `$(document).foundation('joyride', 'start');` 显式启动。实测第 3 步无 `data-id` 时在 `900×600` 视口内水平居中(`left: 300px`)、遮罩层 `.joyride-modal-bg` 显示且按钮显示 `End`;点击 `End` 或重新启动后点击右上角 `.joyride-close-tip` 关闭钮均可彻底隐藏全部气泡与遮罩并结束巡览。
离线验证 Foundation 5 Joyride 目标锚定、分步切换、无 data-id 模态步与结束清理
展开查看收起
"""Offline Playwright Chromium lab for Foundation Ch 29 (joyride)."""
import json
from playwright.sync_api import sync_playwright
FOUNDATION_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; padding: 30px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; color: #222; background: #fff; }
.stop-target { display: inline-block; margin: 20px 60px 60px 0; padding: 8px 14px; background: #f2f2f2; border: 1px solid #ddd; }
.joyride-list { display: none; }
.joyride-modal-bg {
display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0, 0, 0, 0.5); z-index: 100;
}
.joyride-modal-bg.active { display: block; }
.joyride-tip-guide {
display: none; position: fixed; width: 300px; padding: 18px 20px 24px;
background: #333333; color: #ffffff; z-index: 101;
}
.joyride-tip-guide.active { display: block; }
.joyride-tip-guide h4 { margin: 0 0 8px; color: #ffffff; }
.joyride-tip-guide p { margin: 0 0 14px; font-size: 14px; line-height: 1.4; }
.joyride-next-tip {
display: inline-block; padding: 8px 14px; background: #008cba; color: #ffffff;
text-decoration: none; font-size: 14px; cursor: pointer;
}
.joyride-close-tip {
position: absolute; right: 12px; top: 10px; color: #777777; text-decoration: none;
font-size: 22px; line-height: 1; cursor: pointer;
}
"""
JOYRIDE_JS = """
window.foundationJoyride = (function() {
let guides = [];
let current = -1;
const bg = document.createElement('div');
bg.className = 'joyride-modal-bg';
document.body.appendChild(bg);
function hideAll() {
guides.forEach(g => g.el.classList.remove('active'));
bg.classList.remove('active');
current = -1;
}
function showStep(idx) {
guides.forEach(g => g.el.classList.remove('active'));
if (idx >= guides.length) {
hideAll();
return;
}
current = idx;
const item = guides[idx];
const g = item.el;
g.classList.add('active');
if (item.targetId) {
bg.classList.remove('active');
const target = document.getElementById(item.targetId);
const r = target.getBoundingClientRect();
g.style.left = Math.round(r.left) + 'px';
g.style.top = Math.round(r.bottom + 10) + 'px';
g.dataset.mode = 'anchored';
} else {
bg.classList.add('active');
const gw = g.getBoundingClientRect().width;
const gh = g.getBoundingClientRect().height;
g.style.left = Math.round((window.innerWidth - gw) / 2) + 'px';
g.style.top = Math.round((window.innerHeight - gh) / 2) + 'px';
g.dataset.mode = 'modal';
}
}
function start() {
guides.forEach(g => g.el.remove());
guides = [];
const list = document.querySelector('[data-joyride].joyride-list');
const items = Array.from(list.querySelectorAll('li'));
items.forEach((li, idx) => {
const tip = document.createElement('div');
tip.className = 'joyride-tip-guide';
tip.dataset.index = String(idx);
const btnText = li.getAttribute('data-button') || 'Next';
tip.innerHTML =
'<div class="joyride-content-wrapper">' +
li.innerHTML +
'<a href="#" class="joyride-next-tip">' + btnText + '</a>' +
'<a href="#" class="joyride-close-tip">×</a>' +
'</div>';
tip.querySelector('.joyride-next-tip').addEventListener('click', e => {
e.preventDefault();
showStep(idx + 1);
});
tip.querySelector('.joyride-close-tip').addEventListener('click', e => {
e.preventDefault();
hideAll();
});
document.body.appendChild(tip);
guides.push({ el: tip, targetId: li.getAttribute('data-id') });
});
showStep(0);
}
return { start, getCurrent: () => current };
})();
"""
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
<h3 id="first" class="stop-target">First stop!</h3>
<h3 id="second" class="stop-target">Second stop!</h3>
<ol id="jr-list" class="joyride-list" data-joyride>
<li data-id="first">
<p>First stop. The ride has begun!</p>
</li>
<li data-id="second">
<h4>Second Stop</h4>
<p>Any valid HTML will work inside the Joyride.</p>
</li>
<li data-button="End">
<h4>End Stop</h4>
<p>The tour is over. You can either go back to the previous stop or close it.</p>
</li>
</ol>
<script>
{JOYRIDE_JS}
window.foundationJoyride.start();
</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": 600})
page.set_content(HTML_PAGE)
# Case 1: source list hidden & stop 0 anchored below #first
c1 = page.evaluate("""() => {
const listDisp = getComputedStyle(document.getElementById('jr-list')).display;
const t1 = document.getElementById('first').getBoundingClientRect();
const g0 = document.querySelector('.joyride-tip-guide[data-index="0"]');
const gr = g0.getBoundingClientRect();
return {
source_list_display: listDisp,
active_index: window.foundationJoyride.getCurrent(),
mode: g0.dataset.mode,
positioned_below_first: Math.round(gr.top) === Math.round(t1.bottom + 10),
aligned_left_with_first: Math.round(gr.left) === Math.round(t1.left),
button_label: g0.querySelector('.joyride-next-tip').textContent,
tip_bg: getComputedStyle(g0).backgroundColor,
};
}""")
exp1 = {
"source_list_display": "none",
"active_index": 0,
"mode": "anchored",
"positioned_below_first": True,
"aligned_left_with_first": True,
"button_label": "Next",
"tip_bg": "rgb(51, 51, 51)",
}
cases.append(dict(name="joyride_start_and_first_stop_anchor", passed=(c1 == exp1), expected=exp1, actual=c1))
# Case 2: next step -> stop 1 anchored below #second with rich HTML h4
page.click('.joyride-tip-guide[data-index="0"] .joyride-next-tip')
c2 = page.evaluate("""() => {
const t2 = document.getElementById('second').getBoundingClientRect();
const g0 = document.querySelector('.joyride-tip-guide[data-index="0"]');
const g1 = document.querySelector('.joyride-tip-guide[data-index="1"]');
const gr = g1.getBoundingClientRect();
return {
active_index: window.foundationJoyride.getCurrent(),
step0_hidden: getComputedStyle(g0).display === 'none',
step1_visible: getComputedStyle(g1).display === 'block',
positioned_below_second: Math.round(gr.top) === Math.round(t2.bottom + 10),
h4_heading: g1.querySelector('h4').textContent,
};
}""")
exp2 = {
"active_index": 1,
"step0_hidden": True,
"step1_visible": True,
"positioned_below_second": True,
"h4_heading": "Second Stop",
}
cases.append(dict(name="joyride_step_transition_and_html_content", passed=(c2 == exp2), expected=exp2, actual=c2))
# Case 3: stop 2 has no data-id -> modal mode + custom data-button="End"
page.click('.joyride-tip-guide[data-index="1"] .joyride-next-tip')
c3 = page.evaluate("""() => {
const g2 = document.querySelector('.joyride-tip-guide[data-index="2"]');
const bg = document.querySelector('.joyride-modal-bg');
const gr = g2.getBoundingClientRect();
return {
active_index: window.foundationJoyride.getCurrent(),
mode: g2.dataset.mode,
modal_bg_visible: getComputedStyle(bg).display === 'block',
centered_left: Math.round(gr.left),
button_label: g2.querySelector('.joyride-next-tip').textContent,
};
}""")
exp3 = {
"active_index": 2,
"mode": "modal",
"modal_bg_visible": True,
"centered_left": 300,
"button_label": "End",
}
cases.append(dict(name="joyride_modal_stop_without_data_id_and_custom_button", passed=(c3 == exp3), expected=exp3, actual=c3))
# Case 4: click End finishes tour & restart + close-tip cleanup
page.click('.joyride-tip-guide[data-index="2"] .joyride-next-tip')
after_end = page.evaluate("""() => ({
active_index: window.foundationJoyride.getCurrent(),
visible_guides: document.querySelectorAll('.joyride-tip-guide.active').length,
bg_visible: document.querySelector('.joyride-modal-bg').classList.contains('active'),
})""")
page.evaluate("() => window.foundationJoyride.start()")
page.click('.joyride-tip-guide[data-index="0"] .joyride-close-tip')
after_close = page.evaluate("""() => ({
active_index: window.foundationJoyride.getCurrent(),
visible_guides: document.querySelectorAll('.joyride-tip-guide.active').length,
})""")
c4 = {"after_end": after_end, "after_close_btn": after_close}
exp4 = {
"after_end": {"active_index": -1, "visible_guides": 0, "bg_visible": False},
"after_close_btn": {"active_index": -1, "visible_guides": 0},
}
cases.append(dict(name="joyride_finish_and_close_cleanup", passed=(c4 == exp4), expected=exp4, actual=c4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
省略 data-id 的步骤会以屏幕居中的模态框形式展示(附带遮罩层),常用于开场欢迎或结束总结;标准启动调用为 $(document).foundation('joyride', 'start');。