import './tooltip.less'; export interface InitialSettings { target: Element; html: Element | string; className?: string; } export default class Tooltip { private el: Element; private target: Element; constructor(settings: InitialSettings) { const { target, html, className } = settings; this.target = target; const el = this.el = document.createElement('div'); el.className = 'x-tooltip' + (className ? ' ' + className : ''); if (typeof html === 'string') { el.insertAdjacentHTML('beforeend', html); } else { el.appendChild(html); } } private calcPosition() { const rect = this.el.getBoundingClientRect(); const targetRect = this.target.getBoundingClientRect(); return { top: targetRect.top + targetRect.height + 12, left: targetRect.left + targetRect.width / 2 - rect.width / 2, }; } public show() { document.body.appendChild(this.el); const position = this.calcPosition(); this.el.setAttribute('style', ` display:block; left:${position.left}px; top: ${position.top}px; `); } public destroy() { document.body.removeChild(this.el); } }