蓝色天空.知识 · 实践 · 创造
我的收藏
Foundation 教程目录 37章
Foundation / LEARN BY DOING

Foundation 图片

核对 Foundation 5 响应式图片默认缩放、.th 与 .radius 缩略图边框及悬停光晕、.clearing-thumbs 灯箱弹窗与 data-caption 富文本描述、.clearing-feature 单缩略图模式。

学完这一章,你能够

  • 核对 Foundation 5 响应式图片默认缩放、.th 与 .radius 缩略图边框及悬停光晕、.clearing-thumbs 灯箱弹窗与 data-caption 富文本描述、.clearing-feature 单缩略图模式。

响应式图片与缩略图基础

Foundation 5 中的图片默认采用响应式规则(`max-width: 100%; height: auto`),会随父容器或视口收窄自动按比例缩放。要创建可点击的缩略图,可用 `<a>` 包裹 `<img>` 并在 `<a>` 上添加 `.th` 类:默认呈现 `4px` 白色边框与柔和阴影,鼠标悬停时外框切换为浅蓝色光晕。本站离线 Playwright Chromium 实测:`.th` 为 `inline-block`、`4px solid rgb(255, 255, 255)` 边框,悬停后阴影变为含 `0, 140, 186` 蓝光的 `box-shadow`;固有 `400×200` 图片在 `600px` 容器内保持 `400×200`,容器缩至 `208px` 后自动等比缩为 `200×100`。

在 `.th` 上继续叠加 `.radius` 类(`<a href="..." class="th radius">`)可获得圆角缩略图。实测对比显示:普通 `.th` 圆角为 `0px`,叠加 `.radius` 后计算 `border-radius` 为 `3px`,同时完整保留 `4px` 白色外框。

Clearing 图片灯箱弹窗与富文本描述

借助 Foundation 5 的 Clearing 灯箱组件,可将缩略图列表一键升级为全屏图片浏览器:在 `<ul>` 上添加 `.clearing-thumbs` 类与 `data-clearing` 属性,每个 `<li>` 内的 `<a class="th">` 指向高清大图 `href`,内部 `<img>` 显示小尺寸缩略图 `src`。因为弹窗交互依赖脚本,页面必须初始化 Foundation JS(`$(document).ready(function() { $(document).foundation(); })`)。

在每张 `<img>` 上添加 `data-caption` 属性即可在灯箱底部展示说明文字,而且该属性支持嵌入 HTML 标签(例如 `data-caption="<h2>Pulpit Rock</h2><p>Located in Norway</p>"`)。本站离线实测点击第 1 张缩略图后灯箱弹出并加载全尺寸大图,成功解析出 `<h2>Pulpit Rock</h2>` 与 `<p>Located in Norway</p>`、计数显示 `1/3`;点击下一张切换为 `Sunrise Skies`(`2/3`),点击关闭按钮后灯箱顺利收起。

仅展示单张主缩略图

若页面空间有限只想露出一张封面图、点击后仍能浏览整组图集,可在 `<ul>` 上追加 `.clearing-feature` 类,并在目标 `<li>` 上添加 `.clearing-featured-img` 类。本站离线实测 3 项图集中前 2 项计算 `display` 均为 `none`,仅带 `.clearing-featured-img` 的第 3 项保持 `list-item` 可见;点击该封面图打开灯箱时直接定位到 `3/3`(`Northern Lights`),点击下一张仍可循环切换回 `1/3`(`The Pulpit Rock`)。

响应式图片默认行为提示

提示主题核心机制说明
响应式图片默认开启Foundation 5 默认对 img 应用 max-width: 100% 与 height: auto,视口或容器变窄时自动等比缩放,无需额外类名。

Clearing 图片描述富文本提示

提示主题属性写法与效果
data-caption 支持 HTML 标签可在 img 的 data-caption 属性中直接编写 HTML 片段(如 <h2>Pulpit Rock</h2><p>Located in Norway</p>),灯箱展开时按富文本渲染。

离线验证 Foundation 5 响应式图片、.th/.radius 缩略图与 Clearing 灯箱弹窗

含完整源码 · 353 行
展开查看收起
python
"""Offline Playwright Chromium lab for Foundation 5 Ch 12 (images)."""
import json
from playwright.sync_api import sync_playwright

FOUNDATION_IMAGES_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 20px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #222; background: #fff; }
img {
  max-width: 100%;
  height: auto;
  display: inline-block;
  vertical-align: middle;
}
.th {
  line-height: 0;
  display: inline-block;
  max-width: 100%;
  border: solid 4px #FFFFFF;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2);
  transition: all 200ms ease-out;
}
.th:hover, .th:focus {
  box-shadow: 0 0 6px 1px rgba(0, 140, 186, 0.5);
}
.th.radius {
  border-radius: 3px;
}
ul.clearing-thumbs {
  list-style: none;
  margin: 0 0 1rem 0;
  padding: 0;
  display: flex;
  gap: 10px;
}
ul.clearing-thumbs.clearing-feature li {
  display: none;
}
ul.clearing-thumbs.clearing-feature li.clearing-featured-img {
  display: list-item;
}
.clearing-blackout {
  display: none;
  position: fixed;
  inset: 0;
  background: #333333;
  color: #ffffff;
  z-index: 998;
  padding: 24px;
  text-align: center;
}
.clearing-blackout.open {
  display: block;
}
.clearing-caption {
  margin-top: 12px;
  font-size: 0.9rem;
  color: #cccccc;
}
"""


def make_svg(w, h, color, label):
    return (
        "data:image/svg+xml;utf8,"
        f"<svg xmlns='http://www.w3.org/2000/svg' width='{w}' height='{h}'>"
        f"<rect width='{w}' height='{h}' fill='{color}'/>"
        f"<text x='{w // 2}' y='{h // 2}' text-anchor='middle' fill='white' font-size='18'>{label}</text>"
        "</svg>"
    )


IMG_PARIS = make_svg(400, 200, "%232b6cb0", "Paris")
IMG_ROCK_SM = make_svg(200, 100, "%2338a169", "Rock-Thumb")
IMG_ROCK_LG = make_svg(600, 400, "%232f855a", "Rock-Full")
IMG_SKIES_SM = make_svg(200, 100, "%233182ce", "Skies-Thumb")
IMG_SKIES_LG = make_svg(600, 400, "%232b6cb0", "Skies-Full")
IMG_LIGHTS_SM = make_svg(200, 100, "%23805ad5", "Lights-Thumb")
IMG_LIGHTS_LG = make_svg(600, 400, "%236b46c1", "Lights-Full")

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_IMAGES_CSS}</style></head>
<body>
  <div id="resp-box" style="width: 600px;">
    <a id="thumb-basic" href="{IMG_PARIS}" class="th">
      <img id="img-basic" src="{IMG_PARIS}" alt="Paris">
    </a>
  </div>
  <div style="margin-top: 16px;">
    <a id="thumb-radius" href="{IMG_PARIS}" class="th radius">
      <img src="{IMG_PARIS}" alt="Paris Radius" width="200" height="100">
    </a>
  </div>

  <ul id="gallery-main" class="clearing-thumbs" data-clearing>
    <li><a href="{IMG_ROCK_LG}" class="th"><img data-caption="&lt;h2&gt;Pulpit Rock&lt;/h2&gt;&lt;p&gt;Located in Norway&lt;/p&gt;" src="{IMG_ROCK_SM}" alt="Rock"></a></li>
    <li><a href="{IMG_SKIES_LG}" class="th"><img data-caption="Sunrise Skies" src="{IMG_SKIES_SM}" alt="Skies"></a></li>
    <li><a href="{IMG_LIGHTS_LG}" class="th"><img data-caption="Northern Lights" src="{IMG_LIGHTS_SM}" alt="Lights"></a></li>
  </ul>

  <ul id="gallery-feature" class="clearing-thumbs clearing-feature" data-clearing>
    <li id="feat-1"><a href="{IMG_ROCK_LG}" class="th"><img data-caption="The Pulpit Rock" src="{IMG_ROCK_SM}" alt="Rock"></a></li>
    <li id="feat-2"><a href="{IMG_SKIES_LG}" class="th"><img data-caption="Sunrise Skies" src="{IMG_SKIES_SM}" alt="Skies"></a></li>
    <li id="feat-3" class="clearing-featured-img"><a href="{IMG_LIGHTS_LG}" class="th"><img data-caption="Northern Lights" src="{IMG_LIGHTS_SM}" alt="Lights"></a></li>
  </ul>

  <div id="clearing-modal" class="clearing-blackout" aria-hidden="true">
    <button id="clearing-close" type="button">×</button>
    <button id="clearing-prev" type="button">Prev</button>
    <button id="clearing-next" type="button">Next</button>
    <div><img id="clearing-visible-img" src="" alt="Preview"></div>
    <div id="clearing-caption" class="clearing-caption"></div>
    <div id="clearing-counter"></div>
  </div>

  <script>
    (function () {{
      const modal = document.getElementById('clearing-modal');
      const vImg = document.getElementById('clearing-visible-img');
      const vCap = document.getElementById('clearing-caption');
      const vCnt = document.getElementById('clearing-counter');
      let currentList = [];
      let currentIdx = 0;

      function renderModal() {{
        const item = currentList[currentIdx];
        vImg.src = item.href;
        vCap.innerHTML = item.caption || '';
        vCnt.textContent = (currentIdx + 1) + '/' + currentList.length;
      }}

      document.querySelectorAll('ul.clearing-thumbs[data-clearing]').forEach((ul) => {{
        const anchors = Array.from(ul.querySelectorAll('li > a'));
        const items = anchors.map((a) => {{
          const im = a.querySelector('img');
          return {{ href: a.getAttribute('href'), caption: im ? (im.getAttribute('data-caption') || '') : '' }};
        }});
        anchors.forEach((a, idx) => {{
          a.addEventListener('click', (e) => {{
            e.preventDefault();
            currentList = items;
            currentIdx = idx;
            modal.classList.add('open');
            modal.setAttribute('aria-hidden', 'false');
            renderModal();
          }});
        }});
      }});

      document.getElementById('clearing-next').addEventListener('click', () => {{
        if (!currentList.length) return;
        currentIdx = (currentIdx + 1) % currentList.length;
        renderModal();
      }});
      document.getElementById('clearing-prev').addEventListener('click', () => {{
        if (!currentList.length) return;
        currentIdx = (currentIdx - 1 + currentList.length) % currentList.length;
        renderModal();
      }});
      document.getElementById('clearing-close').addEventListener('click', () => {{
        modal.classList.remove('open');
        modal.setAttribute('aria-hidden', 'true');
      }});
    }})();
  </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": 1000, "height": 900})
        page.set_content(HTML_PAGE)

        # Case 1: responsive_img_and_th_thumbnail
        wide = page.evaluate("""() => {
            const a = document.getElementById('thumb-basic');
            const img = document.getElementById('img-basic');
            const as = getComputedStyle(a);
            const is = getComputedStyle(img);
            return {
                th_display: as.display,
                th_border: as.borderTopWidth + ' ' + as.borderTopStyle + ' ' + as.borderTopColor,
                th_shadow_idle: as.boxShadow,
                img_max_width: is.maxWidth,
                wide_w: Math.round(img.getBoundingClientRect().width),
                wide_h: Math.round(img.getBoundingClientRect().height),
            };
        }""")
        page.locator("#thumb-basic").hover()
        page.wait_for_function(
            "() => getComputedStyle(document.getElementById('thumb-basic')).boxShadow.includes('0, 140, 186')"
        )
        hover_shadow = page.evaluate("""() => getComputedStyle(document.getElementById('thumb-basic')).boxShadow""")
        narrow = page.evaluate("""() => {
            document.getElementById('resp-box').style.width = '208px';
            const img = document.getElementById('img-basic');
            return {
                narrow_w: Math.round(img.getBoundingClientRect().width),
                narrow_h: Math.round(img.getBoundingClientRect().height),
            };
        }""")
        act_1 = {
            "th_display": wide["th_display"],
            "th_border": wide["th_border"],
            "hover_shadow_changed": hover_shadow != wide["th_shadow_idle"],
            "hover_has_blue_glow": "0, 140, 186" in hover_shadow,
            "img_max_width": wide["img_max_width"],
            "wide_dims": [wide["wide_w"], wide["wide_h"]],
            "narrow_dims": [narrow["narrow_w"], narrow["narrow_h"]],
        }
        exp_1 = {
            "th_display": "inline-block",
            "th_border": "4px solid rgb(255, 255, 255)",
            "hover_shadow_changed": True,
            "hover_has_blue_glow": True,
            "img_max_width": "100%",
            "wide_dims": [400, 200],
            "narrow_dims": [200, 100],
        }
        cases.append({
            "name": "responsive_img_and_th_thumbnail",
            "expected": exp_1,
            "actual": act_1,
            "passed": act_1 == exp_1,
        })

        # Case 2: radius_thumbnail_corners
        act_2 = page.evaluate("""() => {
            const s1 = getComputedStyle(document.getElementById('thumb-basic'));
            const s2 = getComputedStyle(document.getElementById('thumb-radius'));
            return {
                basic_radius: s1.borderRadius,
                radius_th_radius: s2.borderRadius,
                radius_th_border: s2.borderTopWidth,
            };
        }""")
        exp_2 = {
            "basic_radius": "0px",
            "radius_th_radius": "3px",
            "radius_th_border": "4px",
        }
        cases.append({
            "name": "radius_thumbnail_corners",
            "expected": exp_2,
            "actual": act_2,
            "passed": act_2 == exp_2,
        })

        # Case 3: clearing_lightbox_and_html_caption
        page.locator("#gallery-main li").nth(0).locator("a").click()
        s_open = page.evaluate("""() => ({
            open: document.getElementById('clearing-modal').classList.contains('open'),
            caption_h2: document.querySelector('#clearing-caption h2')?.textContent || '',
            caption_p: document.querySelector('#clearing-caption p')?.textContent || '',
            counter: document.getElementById('clearing-counter').textContent,
            uses_full_href: document.getElementById('clearing-visible-img').src.includes('Rock-Full'),
        })""")
        page.locator("#clearing-next").click()
        s_next = page.evaluate("""() => ({
            caption_text: document.getElementById('clearing-caption').textContent,
            counter: document.getElementById('clearing-counter').textContent,
            uses_full_href: document.getElementById('clearing-visible-img').src.includes('Skies-Full'),
        })""")
        page.locator("#clearing-close").click()
        s_closed = page.evaluate("""() => document.getElementById('clearing-modal').classList.contains('open')""")
        act_3 = {
            "opened": s_open["open"],
            "html_caption_h2": s_open["caption_h2"],
            "html_caption_p": s_open["caption_p"],
            "first_counter": s_open["counter"],
            "first_full_img": s_open["uses_full_href"],
            "next_caption": s_next["caption_text"],
            "next_counter": s_next["counter"],
            "next_full_img": s_next["uses_full_href"],
            "closed_after_click": not s_closed,
        }
        exp_3 = {
            "opened": True,
            "html_caption_h2": "Pulpit Rock",
            "html_caption_p": "Located in Norway",
            "first_counter": "1/3",
            "first_full_img": True,
            "next_caption": "Sunrise Skies",
            "next_counter": "2/3",
            "next_full_img": True,
            "closed_after_click": True,
        }
        cases.append({
            "name": "clearing_lightbox_and_html_caption",
            "expected": exp_3,
            "actual": act_3,
            "passed": act_3 == exp_3,
        })

        # Case 4: clearing_feature_single_thumb
        vis_before = page.evaluate("""() => ({
            li1: getComputedStyle(document.getElementById('feat-1')).display,
            li2: getComputedStyle(document.getElementById('feat-2')).display,
            li3: getComputedStyle(document.getElementById('feat-3')).display,
        })""")
        page.locator("#feat-3 a").click()
        feat_open = page.evaluate("""() => ({
            open: document.getElementById('clearing-modal').classList.contains('open'),
            caption: document.getElementById('clearing-caption').textContent,
            counter: document.getElementById('clearing-counter').textContent,
        })""")
        page.locator("#clearing-next").click()
        feat_cycle = page.evaluate("""() => ({
            caption: document.getElementById('clearing-caption').textContent,
            counter: document.getElementById('clearing-counter').textContent,
        })""")
        act_4 = {
            "hidden_items": [vis_before["li1"], vis_before["li2"]],
            "featured_display": vis_before["li3"],
            "opened_counter": feat_open["counter"],
            "opened_caption": feat_open["caption"],
            "cycled_counter": feat_cycle["counter"],
            "cycled_caption": feat_cycle["caption"],
        }
        exp_4 = {
            "hidden_items": ["none", "none"],
            "featured_display": "list-item",
            "opened_counter": "3/3",
            "opened_caption": "Northern Lights",
            "cycled_counter": "1/3",
            "cycled_caption": "The Pulpit Rock",
        }
        cases.append({
            "name": "clearing_feature_single_thumb",
            "expected": exp_4,
            "actual": act_4,
            "passed": act_4 == exp_4,
        })

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
在离线 Chromium 中核对 img 等比缩放(400x200 -> 200x100)、.th 悬停蓝光、.radius 3px 圆角、data-caption HTML 渲染及 .clearing-feature 单封面轮播。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a739.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Foundation

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

下载课程关联工程包:Foundation

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

在 <ul class="clearing-thumbs" data-clearing> 上追加 .clearing-feature 类,并在需要显示的那个 <li> 元素上添加 .clearing-featured-img 类。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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