HowTo 组件 – howto-checkbox

摘要

<howto-checkbox> 表示表单中的布尔选项。最常见的复选框类型是双类型,它允许用户在两个选项之间切换 -- 选中和未选中。

该元素在首次创建时尝试自行应用 role="checkbox"tabindex="0" 属性。role 属性帮助辅助技术(如屏幕阅读器)告知用户这是哪种类型的控件。tabindex 属性使该元素加入标签页顺序,使其可通过键盘聚焦和操作。要了解有关这两个主题的更多信息,请查看 What can ARIA do?Using 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> 元素克隆内容比使用 innerHTML 性能更高,因为它避免了额外的 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') 或调用 new 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 运行它们。有关更多详细信息,请参阅 lazy properties 部分。

      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);
    }

属性及其对应的属性应相互镜像。checked 的属性 setter 处理真值/假值,并将这些值反映到属性的状态。有关更多详细信息,请参阅 avoid reentrancy 部分。

    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');
    }

当 observedAttributes 数组中的任何属性发生更改时,都会调用 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() 调用 checked setter 并翻转其状态。由于 _toggleChecked() 仅由用户操作引起,因此它还会分派 change 事件。此事件会冒泡,以模仿 <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);
})();