摘要
<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
元素配對,確保元素具有可存取的名稱。
參考資料
示範
應用實例
<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') 或呼叫新的 HowToCheckbox() 而建立;使用建構函式是建立 shadow DOM 的絕佳位置,不過您應該避免碰觸任何可能無法使用的屬性或 light DOM 子項。
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback()
會在元素插入 DOM 時觸發。建議您設定初始 role
、tabindex
、內部狀態和安裝事件監聽器。
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 會處理三進制/falsy 值,並反映與屬性狀態相符的值。詳情請參閱「避免重覆資料」一節。
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');
}
當 ObservAttributes 陣列中的任何屬性發生變更時,系統會呼叫 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);
})();