HowTo 组件 - howto-tooltip

摘要

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