效果预览:
实现代码:
directive.js
javascript
import { nextTick } from "vue"
function elFover(e) {
// e.el.classList.add('hover')
let res = e.el.getBoundingClientRect()
// console.log(res)
let dom_tooltip = document.querySelector('.c-tooltip')
if(dom_tooltip) {
dom_tooltip.style.display = 'block'
dom_tooltip.querySelector('.ivu-tooltip-inner').innerText = e.val
} else {
let _div = document.createElement('div')
_div.innerHTML = `<div class="c-tooltip ivu-tooltip-popper ivu-tooltip-dark ivu-tooltip-transfer" style="z-index: 1099; position: fixed; will-change: top, left; top: 0px; left: 0px;" x-placement="top">
<div class="ivu-tooltip-content">
<div class="ivu-tooltip-arrow"></div>
<div class="ivu-tooltip-inner">${e.val}</div>
</div>
</div>`
document.body.appendChild(_div)
}
nextTick(() => {
!dom_tooltip && (dom_tooltip = document.querySelector('.c-tooltip'))
let _res = dom_tooltip.getBoundingClientRect()
if(res.top < _res.height) {
dom_tooltip.style.top = res.bottom +'px'
dom_tooltip.setAttribute('x-placement', 'bottom')
} else {
dom_tooltip.style.top = (res.top - _res.height) +'px'
dom_tooltip.setAttribute('x-placement', 'top')
}
if(res.left < (_res.width - res.width)/2) {
dom_tooltip.style.left = 0 +'px'
} else if(window.innerWidth - res.right < (_res.width - res.width)/2) {
dom_tooltip.style.left = (window.innerWidth - _res.width) +'px'
} else {
dom_tooltip.style.left = (res.left + (res.width - _res.width)/2) +'px'
}
})
}
function elLeave() {
let dom_tooltip = document.querySelector('.c-tooltip')
if(dom_tooltip) {
dom_tooltip.style.display = 'none'
}
}
let fb = undefined
export const vFocus = {
mounted: (el, binding) => {
fb = elFover.bind(this, {
el: el,
val: binding.value
})
el.addEventListener('mouseenter', fb)
el.addEventListener('mouseleave', elLeave)
},
// 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode, prevVnode) {
el.removeEventListener('mouseenter', fb)
el.removeEventListener('mouseleave', elLeave)
},
}
main.ts
TypeScript
import { vFocus } from '@/utils/directive.js'
import { createApp } from 'vue'
const app = createApp(App)
app.directive('focus', vFocus)
组件里使用
TypeScript
<i class="md-more" v-focus="'更多'"></i>