参考文档:https://www.bilibili.com/opus/500023412612186477
// 自定义"v-tooltip"指令,实现鼠标悬浮显示文本
Vue.directive('tooltip', {bind(element, binding) {const tooltipText = binding.value;const tooltip = document.createElement('div');tooltip.innerHTML = tooltipText;tooltip.style.position = 'absolute';tooltip.style.display = 'none';tooltip.style.background = '#ffffff';tooltip.style.borderRadius = '4px';tooltip.style.width = '95%';tooltip.style.margin = '0px 40px';tooltip.style.padding = '5px 10px';tooltip.style.fontSize = '12px';tooltip.style.textAlign = 'left';tooltip.style.zIndex = '1000';document.body.appendChild(tooltip);// 执行鼠标悬停在元素和面板上展示,离开后面板消失。setSecondaryMenu(element, tooltip, 1000);}
});/*** 给两个元素绑定事件,鼠标悬停在元素和面板上展示,离开后面板消失。* 原理:* 鼠标放到按钮上,面板显示出来,鼠标移出按钮,面板延迟dt毫秒消失。* 鼠标移出后,面板消失之前,移动到面板上,取消面板的延迟消失* 鼠标移出面板后,同样延时dt毫秒消失* @param {*} element 鼠标悬停的元素* @param {*} tooltip 面板元素* @param {*} delayTime 延迟消失的时间,毫秒(ms)*/
function setSecondaryMenu(element, tooltip, delayTime) {/** 鼠标移开按钮后面板延迟消失的时间(ms) */var delayTask;/**鼠标移入按钮 */element.addEventListener("mouseenter", (event) => {let rect = element.getBoundingClientRect();tooltip.style.display = 'block';tooltip.style.top = rect.bottom + 'px';clearTimeout(delayTask);});/**鼠标移出按钮 */element.addEventListener("mouseleave", (event) => {delayTask = setTimeout(() => {tooltip.style.display = 'none';}, delayTime);});/**鼠标移入面板 */tooltip.addEventListener("mouseenter", (event) => {clearTimeout(delayTask);});/**鼠标移出面板 */tooltip.addEventListener("mouseleave", (event) => {delayTask = setTimeout(() => {tooltip.style.display = 'none';}, delayTime);});
}