如何使用元件 – 操作說明工具提示

摘要

<howto-tooltip> 是一種彈出式視窗,會在元素收到鍵盤焦點,或滑鼠遊標懸停在元素上時,顯示元素相關資訊。觸發工具提示的元素會參照含有 aria-describedby 的工具提示元素。

元素會自行套用角色 tooltip,並將 tabindex 設為 -1,因為工具提示本身永遠無法聚焦。

參考資料

示範

前往 GitHub 觀看即時示範

應用實例

<div class="text">
<label for="name">Your name:</label>
<input id="name" aria-describedby="tp1"/>
<howto-tooltip id="tp1">Ideally your name is Batman</howto-tooltip>
<br>
<label for="cheese">Favourite type of cheese: </label>
<input id="cheese" aria-describedby="tp2"/>
<howto-tooltip id="tp2">Help I am trapped inside a tooltip message</howto-tooltip>

程式碼

class HowtoTooltip extends HTMLElement {

建構函式只會執行需要一次執行一次的工作。

  constructor() {
    super();

這些函式會用於多個位置,而且一律需要繫結正確的參照,因此請一次完成。

    this._show = this._show.bind(this);
    this._hide = this._hide.bind(this);
}

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

  connectedCallback() {
    if (!this.hasAttribute('role'))
      this.setAttribute('role', 'tooltip');

    if (!this.hasAttribute('tabindex'))
      this.setAttribute('tabindex', -1);

    this._hide();

觸發工具提示的元素會參照含有 aria-describedby 的工具提示元素。

    this._target = document.querySelector('[aria-describedby=' + this.id + ']');
    if (!this._target)
      return;

工具提示必須監聽目標中的焦點/模糊處理事件,以及將遊標懸停在目標上方的事件。

    this._target.addEventListener('focus', this._show);
    this._target.addEventListener('blur', this._hide);
    this._target.addEventListener('mouseenter', this._show);
    this._target.addEventListener('mouseleave', this._hide);
  }

disconnectedCallback() 會取消註冊在 connectedCallback() 中設定的事件監聽器。

  disconnectedCallback() {
    if (!this._target)
      return;

移除現有的事件監聽器,這樣即使沒有工具提示,也不會觸發。

    this._target.removeEventListener('focus', this._show);
    this._target.removeEventListener('blur', this._hide);
    this._target.removeEventListener('mouseenter', this._show);
    this._target.removeEventListener('mouseleave', this._hide);
    this._target = null;
  }

  _show() {
    this.hidden = false;
  }

  _hide() {
    this.hidden = true;
  }
}

customElements.define('howto-tooltip', HowtoTooltip);