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

离线验证 Bootstrap 4 表格变体、悬停/深色组合、语义行色与断点响应式滚动

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

BS4_TABLE_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: sans-serif; font-size: 16px; color: #212529; background: #fff; }
table { border-collapse: collapse; }
.table { width: 100%; margin-bottom: 1rem; color: #212529; }
.table th, .table td { padding: 0.75rem; vertical-align: top; border-top: 1px solid #dee2e6; }
.table thead th { vertical-align: bottom; border-bottom: 2px solid #dee2e6; }
.table-sm th, .table-sm td { padding: 0.3rem; }
.table-bordered { border: 1px solid #dee2e6; }
.table-bordered th, .table-bordered td { border: 1px solid #dee2e6; }
.table-borderless th, .table-borderless td, .table-borderless thead th, .table-borderless tbody + tbody { border: 0; }
.table-striped tbody tr:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); }
.table-hover tbody tr:hover { color: #212529; background-color: rgba(0, 0, 0, 0.075); }
.table-primary, .table-primary > th, .table-primary > td { background-color: #b8daff; }
.table-secondary, .table-secondary > th, .table-secondary > td { background-color: #d6d8db; }
.table-success, .table-success > th, .table-success > td { background-color: #c3e6cb; }
.table-info, .table-info > th, .table-info > td { background-color: #bee5eb; }
.table-warning, .table-warning > th, .table-warning > td { background-color: #ffeeba; }
.table-danger, .table-danger > th, .table-danger > td { background-color: #f5c6cb; }
.table-light, .table-light > th, .table-light > td { background-color: #fdfdfe; }
.table-dark, .table-dark > th, .table-dark > td { background-color: #c6c8ca; }
.table-active, .table-active > th, .table-active > td { background-color: rgba(0, 0, 0, 0.075); }
.table .thead-dark th { color: #fff; background-color: #343a40; border-color: #454d55; }
.table .thead-light th { color: #495057; background-color: #e9ecef; border-color: #dee2e6; }
table.table-dark { color: #fff; background-color: #343a40; }
table.table-dark th, table.table-dark td, table.table-dark thead th { border-color: #454d55; }
table.table-dark.table-striped tbody tr:nth-of-type(odd) { background-color: rgba(255, 255, 255, 0.05); }
table.table-dark.table-hover tbody tr:hover { color: #fff; background-color: rgba(255, 255, 255, 0.075); }
.table-responsive { display: block; width: 100%; overflow-x: auto; }
@media (max-width: 575.98px) { .table-responsive-sm { display: block; width: 100%; overflow-x: auto; } }
@media (max-width: 767.98px) { .table-responsive-md { display: block; width: 100%; overflow-x: auto; } }
@media (max-width: 991.98px) { .table-responsive-lg { display: block; width: 100%; overflow-x: auto; } }
@media (max-width: 1199.98px) { .table-responsive-xl { display: block; width: 100%; overflow-x: auto; } }
.wide-table th, .wide-table td { white-space: nowrap; min-width: 110px; }
"""

ROWS_3 = """
<thead><tr><th>Firstname</th><th>Lastname</th><th>Email</th></tr></thead>
<tbody>
  <tr><td>John</td><td>Doe</td><td>john@example.com</td></tr>
  <tr><td>Mary</td><td>Moe</td><td>mary@example.com</td></tr>
  <tr><td>July</td><td>Dooley</td><td>july@example.com</td></tr>
</tbody>
"""

WIDE_COLS = "".join(f"<th>Col{i}</th>" for i in range(1, 12))
WIDE_VALS = "".join(f"<td>Value{i}</td>" for i in range(1, 12))
WIDE_HTML = f'<table class="table wide-table"><thead><tr>{WIDE_COLS}</tr></thead><tbody><tr>{WIDE_VALS}</tr></tbody></table>'

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_TABLE_CSS}</style></head>
<body>
  <table id="t-basic" class="table">{ROWS_3}</table>
  <table id="t-striped" class="table table-striped">{ROWS_3}</table>
  <table id="t-bordered" class="table table-bordered">{ROWS_3}</table>
  <table id="t-borderless" class="table table-borderless">{ROWS_3}</table>
  <table id="t-hover" class="table table-hover">{ROWS_3}</table>
  <table id="t-dark" class="table table-dark">{ROWS_3}</table>
  <table id="t-dark-striped" class="table table-dark table-striped">{ROWS_3}</table>
  <table id="t-dark-hover" class="table table-dark table-hover">{ROWS_3}</table>
  <table id="t-ctx" class="table">
    <tbody>
      <tr class="table-primary"><td>primary</td></tr>
      <tr class="table-success"><td>success</td></tr>
      <tr class="table-danger"><td>danger</td></tr>
      <tr class="table-info"><td>info</td></tr>
      <tr class="table-warning"><td>warning</td></tr>
      <tr class="table-active"><td>active</td></tr>
      <tr class="table-secondary"><td>secondary</td></tr>
      <tr class="table-light"><td>light</td></tr>
      <tr class="table-dark"><td>dark</td></tr>
    </tbody>
  </table>
  <table id="t-head-dark" class="table"><thead class="thead-dark"><tr><th>A</th></tr></thead><tbody><tr><td>1</td></tr></tbody></table>
  <table id="t-head-light" class="table"><thead class="thead-light"><tr><th>A</th></tr></thead><tbody><tr><td>1</td></tr></tbody></table>
  <table id="t-sm" class="table table-bordered table-sm">{ROWS_3}</table>
  <div id="r-all" class="table-responsive">{WIDE_HTML}</div>
  <div id="r-sm" class="table-responsive-sm">{WIDE_HTML}</div>
  <div id="r-md" class="table-responsive-md">{WIDE_HTML}</div>
  <div id="r-lg" class="table-responsive-lg">{WIDE_HTML}</div>
  <div id="r-xl" class="table-responsive-xl">{WIDE_HTML}</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: basic_striped_bordered_borderless
        res1 = page.evaluate("""() => {
            const bTd = getComputedStyle(document.querySelector('#t-basic tbody td'));
            const sOdd = getComputedStyle(document.querySelector('#t-striped tbody tr:nth-child(1)'));
            const sEven = getComputedStyle(document.querySelector('#t-striped tbody tr:nth-child(2)'));
            const bdTd = getComputedStyle(document.querySelector('#t-bordered tbody td'));
            const blTd = getComputedStyle(document.querySelector('#t-borderless tbody td'));
            return {
                basic_td_padding: bTd.paddingTop,
                basic_td_border_top: bTd.borderTopWidth + ' ' + bTd.borderTopStyle,
                striped_odd_bg: sOdd.backgroundColor,
                striped_even_bg: sEven.backgroundColor,
                bordered_left_border: bdTd.borderLeftWidth + ' ' + bdTd.borderLeftStyle,
                borderless_top_border: blTd.borderTopWidth,
            };
        }""")
        expected_1 = {
            "basic_td_padding": "12px",
            "basic_td_border_top": "1px solid",
            "striped_odd_bg": "rgba(0, 0, 0, 0.05)",
            "striped_even_bg": "rgba(0, 0, 0, 0)",
            "bordered_left_border": "1px solid",
            "borderless_top_border": "0px",
        }
        cases.append(dict(name="basic_striped_bordered_borderless", passed=(res1 == expected_1), expected=expected_1, actual=res1))

        # Case 2: hover_and_dark_table_variants
        page.locator("#t-hover tbody tr").first.hover()
        light_hover = page.evaluate("() => getComputedStyle(document.querySelector('#t-hover tbody tr')).backgroundColor")
        page.locator("#t-dark-hover tbody tr").first.hover()
        dark_hover = page.evaluate("() => getComputedStyle(document.querySelector('#t-dark-hover tbody tr')).backgroundColor")
        dark_base = page.evaluate("""() => {
            const d = getComputedStyle(document.getElementById('t-dark'));
            const ds = getComputedStyle(document.querySelector('#t-dark-striped tbody tr:nth-child(1)'));
            return { bg: d.backgroundColor, color: d.color, dark_striped_odd: ds.backgroundColor };
        }""")
        actual_2 = {
            "light_hover_bg": light_hover,
            "dark_bg": dark_base["bg"],
            "dark_color": dark_base["color"],
            "dark_striped_odd_bg": dark_base["dark_striped_odd"],
            "dark_hover_bg": dark_hover,
        }
        expected_2 = {
            "light_hover_bg": "rgba(0, 0, 0, 0.075)",
            "dark_bg": "rgb(52, 58, 64)",
            "dark_color": "rgb(255, 255, 255)",
            "dark_striped_odd_bg": "rgba(255, 255, 255, 0.05)",
            "dark_hover_bg": "rgba(255, 255, 255, 0.075)",
        }
        cases.append(dict(name="hover_and_dark_table_variants", passed=(actual_2 == expected_2), expected=expected_2, actual=actual_2))

        # Case 3: contextual_row_colors
        ctx = page.evaluate("""() => {
            const out = {};
            for (const tr of document.querySelectorAll('#t-ctx tbody tr')) {
                out[tr.className] = getComputedStyle(tr).backgroundColor;
            }
            return out;
        }""")
        expected_3 = {
            "table-primary": "rgb(184, 218, 255)",
            "table-success": "rgb(195, 230, 203)",
            "table-danger": "rgb(245, 198, 203)",
            "table-info": "rgb(190, 229, 235)",
            "table-warning": "rgb(255, 238, 186)",
            "table-active": "rgba(0, 0, 0, 0.075)",
            "table-secondary": "rgb(214, 216, 219)",
            "table-light": "rgb(253, 253, 254)",
            "table-dark": "rgb(198, 200, 202)",
        }
        cases.append(dict(name="contextual_row_colors", passed=(ctx == expected_3), expected=expected_3, actual=ctx))

        # Case 4: thead_colors_and_compact_sm
        res4 = page.evaluate("""() => {
            const hd = getComputedStyle(document.querySelector('#t-head-dark thead th'));
            const hl = getComputedStyle(document.querySelector('#t-head-light thead th'));
            const smTd = getComputedStyle(document.querySelector('#t-sm tbody td'));
            const hBasic = Math.round(document.getElementById('t-bordered').getBoundingClientRect().height);
            const hSm = Math.round(document.getElementById('t-sm').getBoundingClientRect().height);
            return {
                thead_dark: { bg: hd.backgroundColor, color: hd.color },
                thead_light: { bg: hl.backgroundColor, color: hl.color },
                sm_padding: smTd.paddingTop,
                sm_shorter_than_standard: hSm < hBasic,
            };
        }""")
        expected_4 = {
            "thead_dark": {"bg": "rgb(52, 58, 64)", "color": "rgb(255, 255, 255)"},
            "thead_light": {"bg": "rgb(233, 236, 239)", "color": "rgb(73, 80, 87)"},
            "sm_padding": "4.8px",
            "sm_shorter_than_standard": True,
        }
        cases.append(dict(name="thead_colors_and_compact_sm", passed=(res4 == expected_4), expected=expected_4, actual=res4))

        # Case 5: responsive_table_overflow
        resp = {}
        for vw in (500, 700, 900, 1100, 1300):
            page.set_viewport_size({"width": vw, "height": 900})
            resp[str(vw)] = page.evaluate("""() => {
                const check = id => {
                    const el = document.getElementById(id);
                    const s = getComputedStyle(el);
                    return { ox: s.overflowX, scrolls: el.scrollWidth > el.clientWidth };
                };
                return {
                    all: check('r-all'),
                    sm: check('r-sm'),
                    md: check('r-md'),
                    lg: check('r-lg'),
                    xl: check('r-xl'),
                };
            }""")
        expected_5 = {
            "500": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "auto", "scrolls": True},
                "md": {"ox": "auto", "scrolls": True},
                "lg": {"ox": "auto", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "700": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "visible", "scrolls": True},
                "md": {"ox": "auto", "scrolls": True},
                "lg": {"ox": "auto", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "900": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "visible", "scrolls": True},
                "md": {"ox": "visible", "scrolls": True},
                "lg": {"ox": "auto", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "1100": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "visible", "scrolls": True},
                "md": {"ox": "visible", "scrolls": True},
                "lg": {"ox": "visible", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "1300": {
                "all": {"ox": "auto", "scrolls": False},
                "sm": {"ox": "visible", "scrolls": False},
                "md": {"ox": "visible", "scrolls": False},
                "lg": {"ox": "visible", "scrolls": False},
                "xl": {"ox": "visible", "scrolls": False},
            },
        }
        cases.append(dict(name="responsive_table_overflow", passed=(resp == expected_5), expected=expected_5, actual=resp))

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

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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