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

离线 Chromium 实测堆叠/内联表单、.row 与 .form-row 列距及表单验证状态流转

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

BS4_FORMS_CSS = """
* { box-sizing: border-box; }
body { margin: 0; padding: 20px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; line-height: 1.5; }
.wrap { width: 600px; }
.form-group { margin-bottom: 1rem; }
.form-control {
  display: block; width: 100%; height: 38px; padding: 0.375rem 0.75rem;
  font-size: 1rem; line-height: 1.5; color: #495057; background-color: #fff;
  border: 1px solid #ced4da; border-radius: 0.25rem;
}
.form-check { position: relative; display: block; padding-left: 1.25rem; }
.form-check-input { position: absolute; margin-top: 0.3rem; margin-left: -1.25rem; }
.form-check-label { margin-bottom: 0; }
.btn { display: inline-block; padding: 0.375rem 0.75rem; font-size: 1rem; border: 1px solid transparent; border-radius: 0.25rem; }
.btn-primary { color: #fff; background-color: #007bff; border-color: #007bff; }
.form-inline { display: flex; flex-flow: row wrap; align-items: center; }
@media (min-width: 576px) {
  .form-inline label { display: flex; align-items: center; justify-content: center; margin-bottom: 0; }
  .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; }
  .form-inline .form-check { display: flex; align-items: center; justify-content: center; width: auto; padding-left: 0; }
  .form-inline .form-check-input { position: relative; margin-top: 0; margin-right: 0.25rem; margin-left: 0; }
  .mr-sm-2 { margin-right: 0.5rem !important; }
}
.mb-2 { margin-bottom: 0.5rem !important; }
.row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }
.row > .col { flex-basis: 0; flex-grow: 1; max-width: 100%; padding-right: 15px; padding-left: 15px; }
.form-row { display: flex; flex-wrap: wrap; margin-right: -5px; margin-left: -5px; }
.form-row > .col { flex-basis: 0; flex-grow: 1; max-width: 100%; padding-right: 5px; padding-left: 5px; }
.valid-feedback { display: none; width: 100%; margin-top: 0.25rem; font-size: 80%; color: #28a745; }
.invalid-feedback { display: none; width: 100%; margin-top: 0.25rem; font-size: 80%; color: #dc3545; }
.was-validated .form-control:valid { border-color: #28a745; }
.was-validated .form-control:valid ~ .valid-feedback { display: block; }
.was-validated .form-control:invalid { border-color: #dc3545; }
.was-validated .form-control:invalid ~ .invalid-feedback { display: block; }
.was-validated .form-check-input:valid ~ .valid-feedback { display: block; }
.was-validated .form-check-input:invalid ~ .invalid-feedback { display: block; }
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def run():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 860, "height": 700})

        # Case 1: stacked form
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_FORMS_CSS}</style></head><body>
        <div class="wrap">
          <form id="stacked">
            <div class="form-group" id="fg1">
              <label for="email">Email address:</label>
              <input type="email" class="form-control" placeholder="Enter email" id="email">
            </div>
            <div class="form-group">
              <label for="pwd">Password:</label>
              <input type="password" class="form-control" placeholder="Enter password" id="pwd">
            </div>
            <div class="form-group form-check">
              <label class="form-check-label">
                <input class="form-check-input" id="rem" type="checkbox"> Remember me
              </label>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
        </div></body></html>""")
        page.check("#rem")
        actual1 = page.evaluate("""() => {
          const e = document.querySelector('#email');
          const pw = document.querySelector('#pwd');
          const er = e.getBoundingClientRect();
          const pwr = pw.getBoundingClientRect();
          return {
            form_control_display: getComputedStyle(e).display,
            form_control_width_px: Math.round(er.width),
            form_group_margin_bottom: getComputedStyle(document.querySelector('#fg1')).marginBottom,
            stacked_vertically: pwr.top > er.bottom,
            checkbox_checked: document.querySelector('#rem').checked,
          };
        }""")
        expected1 = {
            "form_control_display": "block",
            "form_control_width_px": 600,
            "form_group_margin_bottom": "16px",
            "stacked_vertically": True,
            "checkbox_checked": True,
        }
        cases.append(dict(
            name="stacked_form_layout",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: inline form responsive & spacing (.mr-sm-2 / .mb-2)
        page.set_viewport_size({"width": 960, "height": 600})
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_FORMS_CSS}</style></head><body>
        <form id="compact" class="form-inline">
          <label for="e1">Email address:</label>
          <input type="email" class="form-control" id="e1">
          <label for="p1">Password:</label>
          <input type="password" class="form-control" id="p1">
          <button type="submit" class="btn btn-primary">Submit</button>
        </form>
        <form id="spaced" class="form-inline">
          <label for="e2" class="mr-sm-2">Email address:</label>
          <input type="email" class="form-control mb-2 mr-sm-2" id="e2">
          <label for="p2" class="mr-sm-2">Password:</label>
          <input type="password" class="form-control mb-2 mr-sm-2" id="p2">
          <button type="submit" class="btn btn-primary mb-2">Submit</button>
        </form>
        </body></html>""")
        wide = page.evaluate("""() => {
          const e1 = document.querySelector('#e1');
          const p1 = document.querySelector('#p1');
          const e2 = document.querySelector('#e2');
          return {
            same_row_960px: Math.abs(e1.getBoundingClientRect().top - p1.getBoundingClientRect().top) <= 2,
            compact_mr: getComputedStyle(e1).marginRight,
            spaced_mr: getComputedStyle(e2).marginRight,
            spaced_mb: getComputedStyle(e2).marginBottom,
          };
        }""")
        page.set_viewport_size({"width": 480, "height": 600})
        narrow = page.evaluate("""() => {
          const e1 = document.querySelector('#e1');
          const p1 = document.querySelector('#p1');
          return {
            stacked_below_576px: p1.getBoundingClientRect().top > e1.getBoundingClientRect().bottom,
            narrow_input_display: getComputedStyle(e1).display,
          };
        }""")
        actual2 = {**wide, **narrow}
        expected2 = {
            "same_row_960px": True,
            "compact_mr": "0px",
            "spaced_mr": "8px",
            "spaced_mb": "8px",
            "stacked_below_576px": True,
            "narrow_input_display": "block",
        }
        cases.append(dict(
            name="inline_form_responsive_and_spacing",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: .row vs .form-row gutter comparison
        page.set_viewport_size({"width": 800, "height": 500})
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_FORMS_CSS}</style></head><body>
        <div class="wrap">
          <form>
            <div class="row">
              <div class="col" id="r-c1"><input id="r-i1" type="text" class="form-control"></div>
              <div class="col" id="r-c2"><input id="r-i2" type="password" class="form-control"></div>
            </div>
            <div class="form-row">
              <div class="col" id="fr-c1"><input id="fr-i1" type="text" class="form-control"></div>
              <div class="col" id="fr-c2"><input id="fr-i2" type="password" class="form-control"></div>
            </div>
          </form>
        </div></body></html>""")
        actual3 = page.evaluate("""() => {
          const ri1 = document.querySelector('#r-i1').getBoundingClientRect();
          const ri2 = document.querySelector('#r-i2').getBoundingClientRect();
          const fri1 = document.querySelector('#fr-i1').getBoundingClientRect();
          const fri2 = document.querySelector('#fr-i2').getBoundingClientRect();
          return {
            row_same_line: Math.round(ri1.top) === Math.round(ri2.top),
            row_col_padding_x: getComputedStyle(document.querySelector('#r-c1')).paddingLeft,
            row_gap_px: Math.round(ri2.left - ri1.right),
            form_row_same_line: Math.round(fri1.top) === Math.round(fri2.top),
            form_row_col_padding_x: getComputedStyle(document.querySelector('#fr-c1')).paddingLeft,
            form_row_gap_px: Math.round(fri2.left - fri1.right),
          };
        }""")
        expected3 = {
            "row_same_line": True,
            "row_col_padding_x": "15px",
            "row_gap_px": 30,
            "form_row_same_line": True,
            "form_row_col_padding_x": "5px",
            "form_row_gap_px": 10,
        }
        cases.append(dict(
            name="form_grid_row_vs_form_row",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: .was-validated & .needs-validation JS flow
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_FORMS_CSS}</style></head><body>
        <form id="f-was" class="was-validated">
          <div class="form-group">
            <input type="text" class="form-control" id="w-uname" required>
            <div class="valid-feedback" id="w-vf">验证成功!</div>
            <div class="invalid-feedback" id="w-if">请输入用户名!</div>
          </div>
        </form>
        <form id="f-needs" class="needs-validation" novalidate>
          <div class="form-group">
            <input type="text" class="form-control" id="n-uname" required>
            <div class="valid-feedback" id="n-vf">验证成功!</div>
            <div class="invalid-feedback" id="n-if">请输入用户名!</div>
          </div>
          <div class="form-group form-check">
            <label class="form-check-label">
              <input class="form-check-input" id="n-agree" type="checkbox" required> 同意协议
              <div class="valid-feedback">验证成功!</div>
              <div class="invalid-feedback">同意协议才能提交。</div>
            </label>
          </div>
          <button id="n-btn" type="submit" class="btn btn-primary">提交</button>
        </form>
        <script>
        window.__submitted = 0;
        const form = document.querySelector('#f-needs');
        form.addEventListener('submit', function(event) {{
          event.preventDefault();
          if (form.checkValidity() === false) {{
            event.stopPropagation();
          }} else {{
            window.__submitted += 1;
          }}
          form.classList.add('was-validated');
        }}, false);
        </script></body></html>""")
        was_empty = page.evaluate("""() => ({
          border: getComputedStyle(document.querySelector('#w-uname')).borderColor,
          invalidDisp: getComputedStyle(document.querySelector('#w-if')).display,
          validDisp: getComputedStyle(document.querySelector('#w-vf')).display,
        })""")
        page.fill("#w-uname", "alice")
        was_filled = page.evaluate("""() => ({
          border: getComputedStyle(document.querySelector('#w-uname')).borderColor,
          invalidDisp: getComputedStyle(document.querySelector('#w-if')).display,
          validDisp: getComputedStyle(document.querySelector('#w-vf')).display,
        })""")
        needs_init_border = page.evaluate("() => getComputedStyle(document.querySelector('#n-uname')).borderColor")
        page.click("#n-btn")
        needs_after_empty = page.evaluate("""() => ({
          hasWasValidated: document.querySelector('#f-needs').classList.contains('was-validated'),
          invalidDisp: getComputedStyle(document.querySelector('#n-if')).display,
          submitted: window.__submitted,
        })""")
        page.fill("#n-uname", "bob")
        page.check("#n-agree")
        page.click("#n-btn")
        needs_after_valid = page.evaluate("""() => ({
          validDisp: getComputedStyle(document.querySelector('#n-vf')).display,
          submitted: window.__submitted,
        })""")
        actual4 = {
            "was_empty_border": was_empty["border"],
            "was_empty_invalid_display": was_empty["invalidDisp"],
            "was_filled_border": was_filled["border"],
            "was_filled_valid_display": was_filled["validDisp"],
            "needs_init_border": needs_init_border,
            "needs_empty_submit_adds_class": needs_after_empty["hasWasValidated"],
            "needs_empty_submit_blocked": needs_after_empty["submitted"] == 0,
            "needs_empty_invalid_display": needs_after_empty["invalidDisp"],
            "needs_valid_submit_count": needs_after_valid["submitted"],
            "needs_valid_feedback_display": needs_after_valid["validDisp"],
        }
        expected4 = {
            "was_empty_border": "rgb(220, 53, 69)",
            "was_empty_invalid_display": "block",
            "was_filled_border": "rgb(40, 167, 69)",
            "was_filled_valid_display": "block",
            "needs_init_border": "rgb(206, 212, 218)",
            "needs_empty_submit_adds_class": True,
            "needs_empty_submit_blocked": True,
            "needs_empty_invalid_display": "block",
            "needs_valid_submit_count": 1,
            "needs_valid_feedback_display": "block",
        }
        cases.append(dict(
            name="form_validation_states",
            expected=expected4,
            actual=actual4,
            passed=(actual4 == expected4),
        ))

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


if __name__ == "__main__":
    run()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/bootstrap4-forms-lab/explore-forms.py

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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