UNPKG

vvcomponent

Version:
78 lines 2.78 kB
class HoverToolTip extends HTMLElement { static get observedAttributes() { return ['text', 'position', "width"]; } constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.innerHTML = `<style> ${this.#genStyle("above")} </style> <div class="tooltip"> <slot></slot> <div class="tooltiptext"></div> </div>`; } connectedCallback() { setInterval(() => { this.shadowRoot.querySelector('style').innerText = this.#genStyle(this.getAttribute('position')); }, 100); } attributeChangedCallback(name, oldValue, newValue) { if (oldValue == newValue) return; if (name == 'text' && newValue.trim()) { this.getToolTipText().innerHTML = newValue; this.shadowRoot.querySelector('style').innerText = this.#genStyle(this.getAttribute('position')); } else if (name == 'position') { if (newValue == 'above' || newValue == 'below') { this.shadowRoot.querySelector('style').innerText = this.#genStyle(newValue); } else { console.error('Invalid value for attribute "position"'); } } else if (name == 'width') { this.shadowRoot.querySelector('style').innerText = this.#genStyle(this.getAttribute('position')); } } getToolTipText() { return this.shadowRoot.querySelector('.tooltiptext'); } #genStyle(position) { return ` .tooltip { position: relative; display: inline-block; cursor: pointer; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } .tooltiptext { visibility: hidden; width: ${this.getAttribute('width') || "160"}px; min-width: 80px; background-color: #333; color: #fff; text-align: center; border-radius: 8px; padding: 5px; position: absolute; z-index: 1; ${position == "above" ? "bottom" : "top"}: 125%; left: 50%; margin-left: ${0 - (Number(this.getAttribute("width") || "160") / 2)}; opacity: 0; transition: opacity 0.3s; } .tooltiptext::after { content: ""; position: absolute; top: ${position == "above" ? "100%" : `calc(100% - ${this.getToolTipText().offsetHeight}px - 10px)`}; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: ${position == "above" ? "#333 transparent transparent transparent" : "transparent transparent #333 transparent"}; }` } } customElements.define('iftc-hover-tooltip', HoverToolTip);