ui-lib/lib/ui/tooltip.js
2023-03-29 18:25:05 +08:00

58 lines
1.8 KiB
JavaScript

function setTooltip(container, content) {
const wrapper = document.createElement('div');
wrapper.className = 'tooltip-wrapper tooltip-color';
wrapper.style.visibility = 'hidden';
wrapper.style.opacity = 0;
const pointer = document.createElement('div');
pointer.className = 'tooltip-pointer tooltip-color';
const curtain = document.createElement('div');
curtain.className = 'tooltip-curtain tooltip-color';
wrapper.append(pointer, curtain);
const cnt = document.createElement('div');
cnt.className = 'tooltip-content';
if (content instanceof HTMLElement) {
cnt.appendChild(content);
} else {
cnt.innerText = content;
}
wrapper.appendChild(cnt);
container.insertAdjacentElement('afterend', wrapper);
let tid;
container.addEventListener('mouseenter', () => {
tid && clearTimeout(tid);
tid = setTimeout(() => {
const left = container.offsetLeft + container.offsetWidth / 2 - wrapper.offsetWidth / 2;
const top = container.offsetTop - wrapper.offsetHeight - 14;
wrapper.style.left = `${left}px`;
wrapper.style.top = `${top}px`;
wrapper.style.visibility = 'visible';
wrapper.style.opacity = 1;
}, 100);
});
container.addEventListener('mouseleave', () => {
tid && clearTimeout(tid);
tid = setTimeout(() => {
wrapper.style.visibility = 'hidden';
wrapper.style.opacity = 0;
}, 300);
});
}
function resolveTooltip(container) {
const tips = container.querySelectorAll('[title]');
for (let tip of tips) {
const title = tip.getAttribute('title');
if (title != null) {
tip.removeAttribute('title');
setTooltip(tip, title);
}
}
return container;
}
export {
setTooltip,
resolveTooltip
}