คอมโพเนนต์วิธีการ – วิธีการ-เคล็ดลับเครื่องมือ

สรุป

<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, สถานะภายใน และ Listener เหตุการณ์

  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() ยกเลิกการลงทะเบียน Listener เหตุการณ์ที่ตั้งค่าไว้ใน connectedCallback()

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

นำ Listener ที่มีอยู่ออก เพื่อไม่ให้ Listener เริ่มทำงาน แม้ว่าจะไม่มีเคล็ดลับเครื่องมือที่จะแสดง

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