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

离线验证 Bootstrap 4 图像形状、浮动对齐、块级居中与 .img-fluid 等比缩放

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-images.py
explore-images.py167 行
"""Offline Playwright Chromium lab for Bootstrap 4 Ch 07 (images)."""
import json
from urllib.parse import quote
from playwright.sync_api import sync_playwright


def svg_data_uri(w: int, h: int, color: str) -> str:
    svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}"><rect width="{w}" height="{h}" fill="{color}"/></svg>'
    return "data:image/svg+xml;utf8," + quote(svg)


IMG_200 = svg_data_uri(200, 150, "#4a90d9")
IMG_800 = svg_data_uri(800, 400, "#2e7d32")

BS4_IMG_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: sans-serif; }
.rounded { border-radius: 0.25rem !important; }
.rounded-circle { border-radius: 50% !important; }
.img-thumbnail { padding: 0.25rem; background-color: #fff; border: 1px solid #dee2e6; border-radius: 0.25rem; max-width: 100%; height: auto; }
.float-left { float: left !important; }
.float-right { float: right !important; }
.clearfix::after { display: block; clear: both; content: ""; }
.mx-auto { margin-right: auto !important; margin-left: auto !important; }
.d-block { display: block !important; }
.img-fluid { max-width: 100%; height: auto; }
.stage { width: 800px; margin: 0; }
.fluid-wrap { width: 100%; padding: 0 15px; }
"""

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_IMG_CSS}</style></head>
<body>
  <div class="stage">
    <img id="img-rounded" src="{IMG_200}" class="rounded" alt="rounded">
    <img id="img-circle" src="{IMG_200}" class="rounded-circle" alt="circle">
    <img id="img-thumb" src="{IMG_200}" class="img-thumbnail" alt="thumb">
  </div>
  <div id="float-stage" class="stage clearfix">
    <img id="img-fl" src="{IMG_200}" class="float-left" alt="left">
    <img id="img-fr" src="{IMG_200}" class="float-right" alt="right">
  </div>
  <div id="center-stage" class="stage">
    <img id="img-mx-only" src="{IMG_200}" class="mx-auto" alt="inline">
    <img id="img-mx-block" src="{IMG_200}" class="mx-auto d-block" alt="centered">
  </div>
  <div id="fluid-stage" class="fluid-wrap">
    <img id="img-fluid" src="{IMG_800}" class="img-fluid" alt="fluid">
  </div>
</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: image_shape_classes
        res1 = page.evaluate("""() => {
            const sr = getComputedStyle(document.getElementById('img-rounded'));
            const sc = getComputedStyle(document.getElementById('img-circle'));
            const st = getComputedStyle(document.getElementById('img-thumb'));
            return {
                rounded_radius: sr.borderRadius,
                circle_radius: sc.borderRadius,
                thumb_padding: st.paddingTop,
                thumb_border: st.borderTopWidth + ' ' + st.borderTopStyle + ' ' + st.borderTopColor,
                thumb_radius: st.borderRadius,
                thumb_bg: st.backgroundColor,
            };
        }""")
        expected_1 = {
            "rounded_radius": "4px",
            "circle_radius": "50%",
            "thumb_padding": "4px",
            "thumb_border": "1px solid rgb(222, 226, 230)",
            "thumb_radius": "4px",
            "thumb_bg": "rgb(255, 255, 255)",
        }
        cases.append(dict(name="image_shape_classes", passed=(res1 == expected_1), expected=expected_1, actual=res1))

        # Case 2: float_left_and_right_alignment
        res2 = page.evaluate("""() => {
            const box = document.getElementById('float-stage').getBoundingClientRect();
            const l = document.getElementById('img-fl');
            const r = document.getElementById('img-fr');
            const lr = l.getBoundingClientRect();
            const rr = r.getBoundingClientRect();
            return {
                left_float: getComputedStyle(l).float,
                right_float: getComputedStyle(r).float,
                left_x: Math.round(lr.left - box.left),
                right_edge: Math.round(rr.right - box.left),
                same_row: Math.round(lr.top) === Math.round(rr.top),
            };
        }""")
        expected_2 = {
            "left_float": "left",
            "right_float": "right",
            "left_x": 0,
            "right_edge": 800,
            "same_row": True,
        }
        cases.append(dict(name="float_left_and_right_alignment", passed=(res2 == expected_2), expected=expected_2, actual=res2))

        # Case 3: center_image_mx_auto_d_block
        res3 = page.evaluate("""() => {
            const box = document.getElementById('center-stage').getBoundingClientRect();
            const inlineEl = document.getElementById('img-mx-only');
            const blockEl = document.getElementById('img-mx-block');
            return {
                mx_only_display: getComputedStyle(inlineEl).display,
                mx_only_left: Math.round(inlineEl.getBoundingClientRect().left - box.left),
                mx_block_display: getComputedStyle(blockEl).display,
                mx_block_left: Math.round(blockEl.getBoundingClientRect().left - box.left),
                mx_block_right_gap: Math.round(box.right - blockEl.getBoundingClientRect().right),
            };
        }""")
        expected_3 = {
            "mx_only_display": "inline",
            "mx_only_left": 0,
            "mx_block_display": "block",
            "mx_block_left": 300,
            "mx_block_right_gap": 300,
        }
        cases.append(dict(name="center_image_mx_auto_d_block", passed=(res3 == expected_3), expected=expected_3, actual=res3))

        # Case 4: responsive_img_fluid_scaling
        page.set_viewport_size({"width": 375, "height": 800})
        narrow = page.evaluate("""() => {
            const el = document.getElementById('img-fluid');
            const r = el.getBoundingClientRect();
            const s = getComputedStyle(el);
            return { w: Math.round(r.width), h: Math.round(r.height), max_w: s.maxWidth };
        }""")
        page.set_viewport_size({"width": 1200, "height": 800})
        wide = page.evaluate("""() => {
            const r = document.getElementById('img-fluid').getBoundingClientRect();
            return { w: Math.round(r.width), h: Math.round(r.height) };
        }""")
        actual_4 = {"viewport_375": narrow, "viewport_1200": wide}
        expected_4 = {
            "viewport_375": {"w": 345, "h": 173, "max_w": "100%"},
            "viewport_1200": {"w": 800, "h": 400},
        }
        cases.append(dict(name="responsive_img_fluid_scaling", passed=(actual_4 == expected_4), expected=expected_4, actual=actual_4))

        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/bootstrap4-images-lab/explore-images.py

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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