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

离线 Chromium 实测自定义复选/单选伪元素切换、选择菜单三档高度及滑块/文件控件

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

BS4_CUSTOM_CSS = """
* { box-sizing: border-box; }
body { margin: 16px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; line-height: 1.5; }
.wrap { width: 480px; }
.custom-control { position: relative; z-index: 1; display: block; min-height: 1.5rem; padding-left: 1.5rem; }
.custom-control-inline { display: inline-flex; margin-right: 1rem; }
.custom-control-input { position: absolute; left: 0; z-index: -1; width: 1rem; height: 1.25rem; opacity: 0; }
.custom-control-label { position: relative; display: inline-block; margin-bottom: 0; vertical-align: top; cursor: pointer; }
.custom-control-label::before {
  position: absolute; top: 0.25rem; left: -1.5rem; display: block; width: 1rem; height: 1rem;
  pointer-events: none; content: ""; background-color: #fff; border: 1px solid #adb5bd;
}
.custom-checkbox .custom-control-label::before { border-radius: 0.25rem; }
.custom-radio .custom-control-label::before { border-radius: 50%; }
.custom-control-input:checked ~ .custom-control-label::before {
  color: #fff; border-color: #007bff; background-color: #007bff;
}
.custom-select {
  display: inline-block; width: 100%; height: 38px; padding: 0.375rem 1.75rem 0.375rem 0.75rem;
  font-size: 1rem; line-height: 1.5; color: #495057; vertical-align: middle;
  background: #fff url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right 0.75rem center/8px 10px;
  border: 1px solid #ced4da; border-radius: 0.25rem; appearance: none; -webkit-appearance: none;
}
.custom-select-sm { height: 31px; padding-top: 0.25rem; padding-bottom: 0.25rem; padding-left: 0.5rem; font-size: 0.875rem; }
.custom-select-lg { height: 48px; padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; font-size: 1.25rem; }
.custom-range { width: 100%; height: 1.4rem; padding: 0; background-color: transparent; appearance: none; -webkit-appearance: none; }
.custom-file { position: relative; display: inline-block; width: 100%; height: 38px; margin-bottom: 0; }
.custom-file-input { position: relative; z-index: 2; width: 100%; height: 38px; margin: 0; opacity: 0; }
.custom-file-label {
  position: absolute; top: 0; right: 0; left: 0; z-index: 1; height: 38px;
  padding: 0.375rem 0.75rem; line-height: 1.5; color: #495057; background-color: #fff;
  border: 1px solid #ced4da; border-radius: 0.25rem;
}
.custom-file-label::after {
  position: absolute; top: 0; right: 0; bottom: 0; z-index: 3; display: block; height: 36px;
  padding: 0.375rem 0.75rem; line-height: 1.5; color: #495057; content: "Browse";
  background-color: #e9ecef; border-left: inherit; border-radius: 0 0.25rem 0.25rem 0;
}
"""


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": 800, "height": 700})
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_CUSTOM_CSS}</style></head><body>
        <div class="wrap">
          <div class="custom-control custom-checkbox">
            <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
            <label id="lbl-cb" class="custom-control-label" for="customCheck">自定义复选框</label>
          </div>
          <div class="custom-control custom-radio">
            <input type="radio" class="custom-control-input" id="customRadio" name="example1" value="customEx">
            <label id="lbl-rd" class="custom-control-label" for="customRadio">自定义单选框</label>
          </div>
          <div id="inline-group">
            <div class="custom-control custom-radio custom-control-inline">
              <input type="radio" class="custom-control-input" id="cr1" name="inex" value="1">
              <label class="custom-control-label" for="cr1">自定义单选框 1</label>
            </div>
            <div class="custom-control custom-radio custom-control-inline">
              <input type="radio" class="custom-control-input" id="cr2" name="inex" value="2">
              <label class="custom-control-label" for="cr2">自定义单选框 2</label>
            </div>
          </div>

          <select id="sel-def" class="custom-select"><option value="a">Default</option><option value="b">Opt B</option></select>
          <select id="sel-sm" class="custom-select custom-select-sm"><option>Small</option></select>
          <select id="sel-lg" class="custom-select custom-select-lg"><option>Large</option></select>

          <label for="customRange">自定义滑块控件</label>
          <input type="range" class="custom-range" id="customRange" min="0" max="100" value="50">

          <div class="custom-file">
            <input type="file" class="custom-file-input" id="customFile">
            <label id="file-lbl" class="custom-file-label" for="customFile">选择文件</label>
          </div>
        </div>
        <script>
        document.querySelector('#customFile').addEventListener('change', function() {{
          const name = this.dataset.mockFile || (this.files && this.files[0] ? this.files[0].name : '选择文件');
          document.querySelector('#file-lbl').textContent = name;
        }});
        </script></body></html>""")

        # Case 1: custom checkbox, custom radio, inline layout
        cb_before_bg = page.evaluate("() => getComputedStyle(document.querySelector('#lbl-cb'), '::before').backgroundColor")
        page.click("#lbl-cb")
        page.click("#lbl-rd")
        actual1 = page.evaluate("""(cbBeforeBg) => {
          const cbBefore = getComputedStyle(document.querySelector('#lbl-cb'), '::before');
          const rdBefore = getComputedStyle(document.querySelector('#lbl-rd'), '::before');
          const inl = Array.from(document.querySelectorAll('#inline-group .custom-control-inline'));
          return {
            native_input_opacity: getComputedStyle(document.querySelector('#customCheck')).opacity,
            checkbox_before_bg_unchecked: cbBeforeBg,
            checkbox_checked_after_label_click: document.querySelector('#customCheck').checked,
            checkbox_before_bg_checked: cbBefore.backgroundColor,
            checkbox_radius: cbBefore.borderRadius,
            radio_radius: rdBefore.borderRadius,
            radio_checked_after_label_click: document.querySelector('#customRadio').checked,
            inline_display: getComputedStyle(inl[0]).display,
            inline_same_row: Math.abs(inl[0].getBoundingClientRect().top - inl[1].getBoundingClientRect().top) <= 1,
          };
        }""", cb_before_bg)
        expected1 = {
            "native_input_opacity": "0",
            "checkbox_before_bg_unchecked": "rgb(255, 255, 255)",
            "checkbox_checked_after_label_click": True,
            "checkbox_before_bg_checked": "rgb(0, 123, 255)",
            "checkbox_radius": "4px",
            "radio_radius": "50%",
            "radio_checked_after_label_click": True,
            "inline_display": "inline-flex",
            "inline_same_row": True,
        }
        cases.append(dict(
            name="custom_checkbox_radio_and_inline",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: custom select & sm/lg sizes
        page.select_option("#sel-def", "b")
        actual2 = page.evaluate("""() => ({
          appearance: getComputedStyle(document.querySelector('#sel-def')).appearance,
          has_svg_caret_bg: getComputedStyle(document.querySelector('#sel-def')).backgroundImage.includes('data:image/svg+xml'),
          selected_value: document.querySelector('#sel-def').value,
          heights_sm_def_lg_px: [
            Math.round(document.querySelector('#sel-sm').getBoundingClientRect().height),
            Math.round(document.querySelector('#sel-def').getBoundingClientRect().height),
            Math.round(document.querySelector('#sel-lg').getBoundingClientRect().height),
          ],
        })""")
        expected2 = {
            "appearance": "none",
            "has_svg_caret_bg": True,
            "selected_value": "b",
            "heights_sm_def_lg_px": [31, 38, 48],
        }
        cases.append(dict(
            name="custom_select_and_sizes",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: custom range & custom file
        page.evaluate("""() => {
          const r = document.querySelector('#customRange');
          r.value = '75';
          const f = document.querySelector('#customFile');
          f.dataset.mockFile = 'report.pdf';
          f.dispatchEvent(new Event('change'));
        }""")
        actual3 = page.evaluate("""() => {
          const r = document.querySelector('#customRange');
          const fi = document.querySelector('#customFile');
          const fl = document.querySelector('#file-lbl');
          return {
            range_width_px: Math.round(r.getBoundingClientRect().width),
            range_value: r.value,
            file_input_opacity: getComputedStyle(fi).opacity,
            file_label_height_px: Math.round(fl.getBoundingClientRect().height),
            file_label_after_content: getComputedStyle(fl, '::after').content,
            file_label_updated_text: fl.textContent,
          };
        }""")
        expected3 = {
            "range_width_px": 480,
            "range_value": "75",
            "file_input_opacity": "0",
            "file_label_height_px": 38,
            "file_label_after_content": '"Browse"',
            "file_label_updated_text": "report.pdf",
        }
        cases.append(dict(
            name="custom_range_and_file",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

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

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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