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

离线验证 Foundation 5 提醒框满宽配色、圆角、× 码点与点击关闭移除交互

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

FOUNDATION_ALERT_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 16px; font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; }
.wrap { width: 600px; }
.alert-box {
  border: 1px solid #0078a0; display: block; font-size: 0.8125rem; font-weight: normal;
  margin-bottom: 1.25rem; padding: 0.875rem 1.5rem 0.875rem 0.875rem; position: relative;
  background-color: #008CBA; color: #ffffff; width: 100%; border-radius: 0px;
}
.alert-box.secondary { background-color: #e7e7e7; border-color: #c7c7c7; color: #4f4f4f; }
.alert-box.success { background-color: #43AC6A; border-color: #3a945b; color: #ffffff; }
.alert-box.info { background-color: #a0d3e8; border-color: #74bfdd; color: #4f4f4f; }
.alert-box.warning { background-color: #f08a24; border-color: #de770f; color: #ffffff; }
.alert-box.alert { background-color: #f04124; border-color: #de2d0f; color: #ffffff; }
.alert-box.radius { border-radius: 3px; }
.alert-box.round { border-radius: 1000px; }
.alert-box .close {
  right: 0.25rem; top: 50%; margin-top: -0.6875rem; position: absolute;
  font-size: 1.375rem; line-height: 0.9; opacity: 0.3; text-decoration: none; color: #333333; cursor: pointer;
}
"""

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_ALERT_CSS}</style></head>
<body>
  <div class="wrap">
    <div id="a-default" data-alert class="alert-box">This is a default alert box.</div>
    <div id="a-secondary" data-alert class="alert-box secondary">This is a secondary alert box.</div>
    <div id="a-success" data-alert class="alert-box success"><strong>Success!</strong> Positive action.</div>
    <div id="a-info" data-alert class="alert-box info"><strong>Info!</strong> Neutral change.</div>
    <div id="a-warning" data-alert class="alert-box warning"><strong>Warning!</strong> Needs attention.</div>
    <div id="a-alert" data-alert class="alert-box alert"><strong>Alert!</strong> Dangerous action.</div>

    <div id="a-radius" data-alert class="alert-box success radius"><strong>Success!</strong> Radius alert.</div>
    <div id="a-round" data-alert class="alert-box info round"><strong>Info!</strong> Round alert.</div>

    <div id="closable-zone">
      <div id="a-close-1" data-alert class="alert-box">
        Closable alert box 1.
        <a id="close-btn-1" href="#" class="close">&times;</a>
      </div>
      <div id="a-close-2" data-alert class="alert-box success">
        Closable alert box 2.
        <a id="close-btn-2" href="#" class="close">&times;</a>
      </div>
    </div>
  </div>
  <script>
    document.querySelectorAll('[data-alert] .close').forEach((btn) => {{
      btn.addEventListener('click', (e) => {{
        e.preventDefault();
        const box = btn.closest('[data-alert]');
        if (box) box.remove();
      }});
    }});
  </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": 900})
        page.set_content(HTML_PAGE)

        # Case 1: 6 alert variants & 100% container width
        actual_1 = page.evaluate("""() => {
            const ids = ['a-default','a-secondary','a-success','a-info','a-warning','a-alert'];
            const variants = {};
            const widths = [];
            for (const id of ids) {
                const el = document.getElementById(id);
                const s = getComputedStyle(el);
                variants[id.slice(2)] = { bg: s.backgroundColor, color: s.color };
                widths.push(Math.round(el.getBoundingClientRect().width));
            }
            return { variants, widths };
        }""")
        expected_1 = {
            "variants": {
                "default": {"bg": "rgb(0, 140, 186)", "color": "rgb(255, 255, 255)"},
                "secondary": {"bg": "rgb(231, 231, 231)", "color": "rgb(79, 79, 79)"},
                "success": {"bg": "rgb(67, 172, 106)", "color": "rgb(255, 255, 255)"},
                "info": {"bg": "rgb(160, 211, 232)", "color": "rgb(79, 79, 79)"},
                "warning": {"bg": "rgb(240, 138, 36)", "color": "rgb(255, 255, 255)"},
                "alert": {"bg": "rgb(240, 65, 36)", "color": "rgb(255, 255, 255)"},
            },
            "widths": [600, 600, 600, 600, 600, 600],
        }
        cases.append({
            "name": "alert_box_six_variants_and_full_width",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: .radius and .round alert corners
        actual_2 = page.evaluate("""() => ({
            default_radius: getComputedStyle(document.getElementById('a-default')).borderRadius,
            radius_class: getComputedStyle(document.getElementById('a-radius')).borderRadius,
            round_class: getComputedStyle(document.getElementById('a-round')).borderRadius
        })""")
        expected_2 = {
            "default_radius": "0px",
            "radius_class": "3px",
            "round_class": "1000px",
        }
        cases.append({
            "name": "alert_box_radius_and_round",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: &times; HTML entity code point vs ASCII 'x'
        actual_3 = page.evaluate("""() => {
            const txt = document.getElementById('close-btn-1').textContent;
            return {
                rendered_char: txt,
                code_point: txt.charCodeAt(0),
                is_ascii_x: txt === 'x'
            };
        }""")
        expected_3 = {
            "rendered_char": "×",
            "code_point": 215,
            "is_ascii_x": False,
        }
        cases.append({
            "name": "times_entity_codepoint_verification",
            "expected": expected_3,
            "actual": actual_3,
            "passed": actual_3 == expected_3,
        })

        # Case 4: clicking .close removes target [data-alert] from DOM
        before_count = page.evaluate("() => document.querySelectorAll('#closable-zone [data-alert]').length")
        page.click("#close-btn-1")
        after_4 = page.evaluate("""() => ({
            before_count: 2,
            after_count: document.querySelectorAll('#closable-zone [data-alert]').length,
            first_removed: !document.getElementById('a-close-1'),
            second_preserved: !!document.getElementById('a-close-2')
        })""")
        after_4["before_count"] = before_count
        expected_4 = {
            "before_count": 2,
            "after_count": 1,
            "first_removed": True,
            "second_preserved": True,
        }
        cases.append({
            "name": "alert_box_close_interaction",
            "expected": expected_4,
            "actual": after_4,
            "passed": after_4 == expected_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/foundation-alerts-lab/explore-alerts.py

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

下载课程关联工程包:Foundation

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

下载课程关联工程包:Foundation

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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