"""Offline Playwright Chromium lab for Foundation Ch 23 (forms)."""
import json
from playwright.sync_api import sync_playwright
FOUNDATION_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; padding: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; color: #222; background: #fff; }
.container { width: 600px; margin: 20px auto; }
form { margin: 0 0 16px; }
label { font-size: 14px; color: #4d4d4d; cursor: pointer; display: block; font-weight: 400; line-height: 1.5; margin-bottom: 0; }
label.right { float: right; text-align: right; }
input[type="text"], textarea, select {
display: block;
width: 100%;
margin: 0 0 16px 0;
padding: 8px;
border: 1px solid #cccccc;
background-color: #ffffff;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
color: rgba(0, 0, 0, 0.75);
font-size: 14px;
}
input[type="text"]:focus, textarea:focus, select:focus {
background: #fafafa;
border-color: #999999;
outline: none;
}
fieldset { border: 1px solid #dddddd; padding: 20px; margin: 18px 0; }
fieldset legend { font-weight: 700; background: #ffffff; padding: 0 3px; margin: 0 0 0 -3px; }
label.error { color: #f04124; }
label.error input, label.error textarea, input.error, textarea.error {
border-color: #f04124;
background-color: rgba(240, 65, 36, 0.1);
margin-bottom: 0;
}
small.error {
display: block;
padding: 6px 9px 9px;
margin-top: -1px;
margin-bottom: 16px;
font-size: 12px;
font-weight: 400;
font-style: italic;
background: #f04124;
color: #ffffff;
}
small.error.hidden { display: none; }
"""
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
<div class="container">
<form id="f-basic">
<input id="basic-input" type="text" placeholder="Name">
<textarea id="basic-textarea" rows="4" placeholder="Address"></textarea>
<select id="basic-select">
<option>1</option><option>2</option><option>3</option><option>4</option>
</select>
</form>
<form id="f-labels">
<label id="lbl-name" for="name">Input
<input type="text" placeholder="Name" id="name">
</label>
<label id="lbl-adr" for="adr">Label
<textarea rows="4" placeholder="Address" id="adr"></textarea>
</label>
<label id="lbl-num" for="num">Select
<select id="num"><option>1</option><option>2</option></select>
</label>
<label id="lbl-right" class="right">Right Aligned Label</label>
</form>
<form id="f-fieldset" style="clear:both;">
<fieldset id="fs">
<legend id="fs-legend">Fieldset Legend</legend>
<label>Name <input type="text" placeholder="First Name.."></label>
<label>Email <input type="text" placeholder="Enter email.."></label>
</fieldset>
</form>
<form id="f-error">
<label id="err-lbl" class="error">Error
<input id="err-input" type="text" placeholder="Name..">
</label>
<small id="err-msg" class="error">Wrong input</small>
<textarea id="err-ta" class="error" rows="4" placeholder="Address"></textarea>
<small id="err-ta-msg" class="error">Wrong input</small>
</form>
</div>
<script>
const errInput = document.getElementById('err-input');
const errLbl = document.getElementById('err-lbl');
const errMsg = document.getElementById('err-msg');
errInput.addEventListener('input', () => {{
const invalid = errInput.value.trim().length < 3;
errLbl.classList.toggle('error', invalid);
errMsg.classList.toggle('hidden', !invalid);
}});
</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: global form controls full width & styling
page.focus("#basic-input")
c1 = page.evaluate("""() => {
const inp = document.getElementById('basic-input');
const ta = document.getElementById('basic-textarea');
const sel = document.getElementById('basic-select');
const is = getComputedStyle(inp);
const ts = getComputedStyle(ta);
const ss = getComputedStyle(sel);
return {
input_width: Math.round(inp.getBoundingClientRect().width),
textarea_width: Math.round(ta.getBoundingClientRect().width),
select_width: Math.round(sel.getBoundingClientRect().width),
margin_bottom: is.marginBottom,
padding_top: is.paddingTop,
has_inset_shadow: is.boxShadow.includes('inset'),
focused_bg: is.backgroundColor,
textarea_margin_bottom: ts.marginBottom,
select_margin_bottom: ss.marginBottom,
};
}""")
exp1 = {
"input_width": 600,
"textarea_width": 600,
"select_width": 600,
"margin_bottom": "16px",
"padding_top": "8px",
"has_inset_shadow": True,
"focused_bg": "rgb(250, 250, 250)",
"textarea_margin_bottom": "16px",
"select_margin_bottom": "16px",
}
cases.append(dict(name="global_form_controls_full_width_and_styles", passed=(c1 == exp1), expected=exp1, actual=c1))
# Case 2: label for/id focus linkage and .right alignment
page.click("#lbl-name")
f1 = page.evaluate("() => document.activeElement.id")
page.click("#lbl-adr")
f2 = page.evaluate("() => document.activeElement.id")
page.click("#lbl-num")
f3 = page.evaluate("() => document.activeElement.id")
right_style = page.evaluate("""() => {
const s = getComputedStyle(document.getElementById('lbl-right'));
return { float: s.float, text_align: s.textAlign };
}""")
c2 = {
"focus_after_label_name": f1,
"focus_after_label_adr": f2,
"focus_after_label_num": f3,
"right_float": right_style["float"],
"right_text_align": right_style["text_align"],
}
exp2 = {
"focus_after_label_name": "name",
"focus_after_label_adr": "adr",
"focus_after_label_num": "num",
"right_float": "right",
"right_text_align": "right",
}
cases.append(dict(name="label_for_focus_and_right_align", passed=(c2 == exp2), expected=exp2, actual=c2))
# Case 3: fieldset & legend styling
c3 = page.evaluate("""() => {
const fs = getComputedStyle(document.getElementById('fs'));
const lg = getComputedStyle(document.getElementById('fs-legend'));
return {
fieldset_border_color: fs.borderTopColor,
fieldset_padding: fs.paddingTop,
fieldset_margin_top: fs.marginTop,
legend_font_weight: lg.fontWeight,
legend_bg: lg.backgroundColor,
};
}""")
exp3 = {
"fieldset_border_color": "rgb(221, 221, 221)",
"fieldset_padding": "20px",
"fieldset_margin_top": "18px",
"legend_font_weight": "700",
"legend_bg": "rgb(255, 255, 255)",
}
cases.append(dict(name="fieldset_and_legend_styling", passed=(c3 == exp3), expected=exp3, actual=c3))
# Case 4: error state styling & JS dynamic validation toggle
before_err = page.evaluate("""() => {
const lbl = getComputedStyle(document.getElementById('err-lbl'));
const inp = getComputedStyle(document.getElementById('err-input'));
const msg = getComputedStyle(document.getElementById('err-msg'));
return {
label_color: lbl.color,
input_border_color: inp.borderTopColor,
small_bg: msg.backgroundColor,
small_color: msg.color,
small_display: msg.display,
};
}""")
page.fill("#err-input", "Alice")
valid_state = page.evaluate("""() => ({
has_error_class: document.getElementById('err-lbl').classList.contains('error'),
small_display: getComputedStyle(document.getElementById('err-msg')).display,
})""")
page.fill("#err-input", "A")
invalid_again = page.evaluate("""() => ({
has_error_class: document.getElementById('err-lbl').classList.contains('error'),
small_display: getComputedStyle(document.getElementById('err-msg')).display,
})""")
c4 = {"initial_error": before_err, "after_valid_input": valid_state, "after_short_input": invalid_again}
exp4 = {
"initial_error": {
"label_color": "rgb(240, 65, 36)",
"input_border_color": "rgb(240, 65, 36)",
"small_bg": "rgb(240, 65, 36)",
"small_color": "rgb(255, 255, 255)",
"small_display": "block",
},
"after_valid_input": {"has_error_class": False, "small_display": "none"},
"after_short_input": {"has_error_class": True, "small_display": "block"},
}
cases.append(dict(name="error_state_and_js_validation", passed=(c4 == exp4), expected=exp4, actual=c4))
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-forms-lab/explore-forms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-forms.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a745.zip
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a739.zip