操作說明元件 - 操作核取方塊

摘要

<howto-checkbox> 代表表單中的布林值選項。最常見的類型 核取方塊屬於雙重類型,可讓使用者在 已勾選和未勾選的選項

元素會嘗試自行套用屬性 role="checkbox"tabindex="0"role 屬性可提供輔助協助 可以透過螢幕閱讀器等技術告訴使用者控制權。 tabindex 屬性會將元素選擇依分頁標籤順序,由鍵盤組成 可聚焦和操作。如要進一步瞭解這兩個主題,請前往 ARIA 有哪些功能?使用 Tabindex

勾選核取方塊後,系統會新增 checked 布林值屬性和組合 將對應的 checked 屬性對應到 true。此外,元素會設定 aria-checked 屬性設為 "true""false",視其屬性而定 時間。按下滑鼠或空格鍵勾選核取方塊, 已勾選狀態。

核取方塊也支援 disabled 狀態。如果 disabled 屬性 設為 true 或套用 disabled 屬性,即表示核取方塊集 aria-disabled="true",移除 tabindex 屬性,然後傳回焦點 如果核取方塊是目前的activeElement,則套用至文件。

核取方塊與 howto-label 元素配對,確保 無障礙名稱

參考資料

示範

前往 GitHub 觀看即時示範

使用案例:

<style>
  howto-checkbox {
    vertical-align: middle;
  }
  howto-label {
    vertical-align: middle;
    display: inline-block;
    font-weight: bold;
    font-family: sans-serif;
    font-size: 20px;
    margin-left: 8px;
  }
</style>

<howto-checkbox id="join-checkbox"></howto-checkbox>
<howto-label for="join-checkbox">Join Newsletter</howto-label>

程式碼

(function() {

請定義按鍵碼來處理鍵盤事件。

  const KEYCODE = {
    SPACE: 32,
  };

<template> 元素複製內容的效果比使用內部 HTML 更好,因為這樣可避免額外的 HTML 剖析成本。

  const template = document.createElement('template');

  template.innerHTML = `
    <style>
      :host {
        display: inline-block;
        background: url('../images/unchecked-checkbox.svg') no-repeat;
        background-size: contain;
        width: 24px;
        height: 24px;
      }
      :host([hidden]) {
        display: none;
      }
      :host([checked]) {
        background: url('../images/checked-checkbox.svg') no-repeat;
        background-size: contain;
      }
      :host([disabled]) {
        background:
          url('../images/unchecked-checkbox-disabled.svg') no-repeat;
        background-size: contain;
      }
      :host([checked][disabled]) {
        background:
          url('../images/checked-checkbox-disabled.svg') no-repeat;
        background-size: contain;
      }
    </style>
  `;


  class HowToCheckbox extends HTMLElement {
    static get observedAttributes() {
      return ['checked', 'disabled'];
    }

每當建立新例項時,就會執行元素的建構函式。實例是透過剖析 HTML、呼叫 document.createElement('howto-checkbox') 或呼叫新的 HowToCheckbox() 方式建立;建構函式是建立 shadow DOM 的好地方,但您應該避免碰觸任何屬性或 light DOM 子項,因為它們可能尚未提供。

    constructor() {
      super();
      this.attachShadow({mode: 'open'});
      this.shadowRoot.appendChild(template.content.cloneNode(true));
    }

connectedCallback() 會在元素插入 DOM 時觸發。建議您設定初始的 roletabindex、內部狀態及安裝事件監聽器。

    connectedCallback() {
      if (!this.hasAttribute('role'))
        this.setAttribute('role', 'checkbox');
      if (!this.hasAttribute('tabindex'))
        this.setAttribute('tabindex', 0);

使用者可以在其原型連結至此類別之前,在元素的實例上設定屬性。_upgradeProperty() 方法會檢查任何執行個體屬性,並透過適當的類別 setter 執行。詳情請參閱「延遲屬性」一節。

      this._upgradeProperty('checked');
      this._upgradeProperty('disabled');

      this.addEventListener('keyup', this._onKeyUp);
      this.addEventListener('click', this._onClick);
    }

    _upgradeProperty(prop) {
      if (this.hasOwnProperty(prop)) {
        let value = this[prop];
        delete this[prop];
        this[prop] = value;
      }
    }

disconnectedCallback() 會在元素從 DOM 移除時觸發。您可以藉此清理工作,例如釋出參照或移除事件監聽器。

    disconnectedCallback() {
      this.removeEventListener('keyup', this._onKeyUp);
      this.removeEventListener('click', this._onClick);
    }

屬性及其對應的屬性應彼此相同。已勾選的屬性 setter 會處理趨勢/虛構值,並將其反映到屬性狀態。詳情請參閱「避免重複記錄」一節。

    set checked(value) {
      const isChecked = Boolean(value);
      if (isChecked)
        this.setAttribute('checked', '');
      else
        this.removeAttribute('checked');
    }

    get checked() {
      return this.hasAttribute('checked');
    }

    set disabled(value) {
      const isDisabled = Boolean(value);
      if (isDisabled)
        this.setAttribute('disabled', '');
      else
        this.removeAttribute('disabled');
    }

    get disabled() {
      return this.hasAttribute('disabled');
    }

當觀察到的屬性陣列中的任何屬性發生變更時,系統就會呼叫 attributeChangedCallback()。這個階段很適合處理副作用,例如設定 ARIA 屬性。

    attributeChangedCallback(name, oldValue, newValue) {
      const hasValue = newValue !== null;
      switch (name) {
        case 'checked':
          this.setAttribute('aria-checked', hasValue);
          break;
        case 'disabled':
          this.setAttribute('aria-disabled', hasValue);

tabindex 屬性無法完全移除元素的可聚焦性。含有 tabindex=-1 的元素仍可透過滑鼠或呼叫 focus() 聚焦。如要確保某個元素已停用且無法聚焦,請移除 tabindex 屬性。

          if (hasValue) {
            this.removeAttribute('tabindex');

如果焦點目前在這個元素上,請呼叫 HTMLElement.blur() 方法,將焦點取消聚焦

            this.blur();
          } else {
            this.setAttribute('tabindex', '0');
          }
          break;
      }
    }

    _onKeyUp(event) {

切勿處理通常由輔助技術使用的輔助快速鍵。

      if (event.altKey)
        return;

      switch (event.keyCode) {
        case KEYCODE.SPACE:
          event.preventDefault();
          this._toggleChecked();
          break;

任何其他按鍵都會遭到忽略並傳回瀏覽器。

        default:
          return;
      }
    }

    _onClick(event) {
      this._toggleChecked();
    }

_toggleChecked() 會呼叫已勾選的 setter 並翻轉其狀態。由於 _toggleChecked() 只會由使用者動作引起,因此也會派出變更事件。這個事件泡泡是用來模擬 <input type=checkbox> 的原生行為。

    _toggleChecked() {
      if (this.disabled)
        return;
      this.checked = !this.checked;
      this.dispatchEvent(new CustomEvent('change', {
        detail: {
          checked: this.checked,
        },
        bubbles: true,
      }));
    }
  }

  customElements.define('howto-checkbox', HowToCheckbox);
})();