示例工程 45-web-component-forms

45-web-component-forms/demo-01-form-value/index.html

html · 5.4 KB

运行:表单值演示

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>表单值演示</title>
    <style>
      body { margin: 0; padding: 32px; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.7; }
      .box { max-width: 720px; margin-bottom: 16px; padding: 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
      h1 { margin: 0 0 16px; font-size: 28px; }
      h2 { margin: 0 0 8px; font-size: 17px; }
      p { margin: 0 0 10px; color: #334155; }
      form { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
      x-stepper { display: inline-flex; }
      .buttons { display: flex; gap: 6px; margin-left: 8px; }
      button { padding: 5px 12px; border: 1px solid #2563eb; border-radius: 6px; background: #2563eb; color: #fff; font: inherit; font-size: 13px; }
      button + button { border-color: #cbd5e1; background: #fff; color: #0f172a; }
      pre { margin: 8px 0 0; padding: 12px; border-radius: 8px; background: #0f172a; color: #e2e8f0; font-size: 12px; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
    </style>
  </head>
  <body>
    <h1>表单值</h1>

    <div class="box">
      <h2>自定义步进器</h2>
      <p>点 + / − 改变数量,<code>FormData</code> 实时更新。</p>
      <form id="f">
        <label for="qty">数量</label>
        <x-stepper id="qty" name="quantity" value="2" min="1" max="9" label="数量"></x-stepper>
        <div class="buttons">
          <button type="submit">提交</button>
          <button type="reset">重置</button>
        </div>
        <pre id="out"></pre>
      </form>
    </div>

    <div class="box">
      <h2>表单成员</h2>
      <p><code>form.elements</code> 里包含这个自定义元素:<span id="member"></span></p>
    </div>

    <script>
      class XStepper extends HTMLElement {
        static formAssociated = true;
        static observedAttributes = ["value", "min", "max", "disabled"];

        constructor() {
          super();
          this.internals = this.attachInternals();
          const root = this.attachShadow({ mode: "open" });
          root.innerHTML = `
            <style>
              :host { display: inline-flex; align-items: center; gap: 6px; padding: 4px 6px; border: 1px solid #cbd5e1; border-radius: 8px; }
              :host([disabled]) { opacity: 0.55; }
              button { width: 28px; height: 28px; border: 1px solid #cbd5e1; border-radius: 6px; background: #fff; font: inherit; }
              output { min-width: 2ch; text-align: center; font-variant-numeric: tabular-nums; }
            </style>
            <button type="button" data-step="-1" aria-label="减少">−</button>
            <output part="value"></output>
            <button type="button" data-step="1" aria-label="增加">+</button>
          `;
          this.output = root.querySelector("output");
          root.querySelectorAll("button").forEach((button) => {
            button.addEventListener("click", () => {
              const step = Number(button.dataset.step);
              this.setValue(this.value + step);
            });
          });
        }

        connectedCallback() {
          this.defaultValue = this.clamp(Number(this.getAttribute("value")) || 0);
          this.setValue(this.defaultValue);
          this.internals.role = "group";
          this.internals.ariaLabel = this.getAttribute("label") ?? "数量";
        }

        attributeChangedCallback() {
          if (this.isConnected) this.sync();
        }

        clamp(value) {
          const min = Number(this.getAttribute("min")) || 0;
          const max = Number(this.getAttribute("max")) || 99;
          return Math.max(min, Math.min(max, value));
        }

        get value() {
          return this._value ?? 0;
        }

        setValue(next) {
          this._value = this.clamp(Number(next) || 0);
          this.sync();
        }

        sync() {
          this.output.textContent = String(this.value);
          this.internals.setFormValue(String(this.value));
          this.internals.ariaValueNow = String(this.value);
          this.internals.ariaValueMin = this.getAttribute("min") ?? "0";
          this.internals.ariaValueMax = this.getAttribute("max") ?? "99";
          this.internals.ariaDisabled = String(this.hasAttribute("disabled"));
          this.shadowRoot.querySelectorAll("button").forEach((button) => {
            button.disabled = this.hasAttribute("disabled");
          });
        }

        formResetCallback() {
          this.setValue(this.defaultValue);
        }

        formDisabledCallback(disabled) {
          this.toggleAttribute("disabled", disabled);
          this.sync();
        }
      }
      customElements.define("x-stepper", XStepper);

      const form = document.getElementById("f");
      const out = document.getElementById("out");
      const show = () => {
        out.textContent = JSON.stringify(Object.fromEntries(new FormData(form).entries()), null, 2);
      };
      form.addEventListener("submit", (event) => {
        event.preventDefault();
        show();
      });
      form.addEventListener("reset", () => setTimeout(show, 0));
      show();
      document.getElementById("member").textContent = form.elements.namedItem("quantity")?.tagName ?? "(未找到)";
    </script>
  </body>
</html>