60 lines
1.6 KiB
Vue
60 lines
1.6 KiB
Vue
<script setup>
|
|||
|
|
import { nextTick, onBeforeUnmount, ref } from 'vue'
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 轻量 Tooltip:替代原生 title 属性。鼠标悬停、键盘聚焦都会显示,位置自动翻转。
|
||
|
|
*/
|
||
|
|
const props = defineProps({
|
||
|
|
content: { type: String, default: '' },
|
||
|
|
placement: { type: String, default: 'top' },
|
||
|
|
delay: { type: Number, default: 120 },
|
||
|
|
disabled: Boolean
|
||
|
|
})
|
||
|
|
|
||
|
|
const rootRef = ref(null)
|
||
|
|
const visible = ref(false)
|
||
|
|
const style = ref({})
|
||
|
|
let timer = 0
|
||
|
|
|
||
|
|
const TEXT_WIDTH = 240
|
||
|
|
|
||
|
|
function measure() {
|
||
|
|
const anchor = rootRef.value
|
||
|
|
if (!anchor) return
|
||
|
|
const rect = anchor.getBoundingClientRect()
|
||
|
|
const place = props.placement === 'bottom' ? 'bottom' : 'top'
|
||
|
|
style.value = {
|
||
|
|
left: `${Math.max(8, Math.min(rect.left + rect.width / 2 - TEXT_WIDTH / 2, window.innerWidth - TEXT_WIDTH - 8))}px`,
|
||
|
|
minWidth: `${Math.min(rect.width, TEXT_WIDTH)}px`,
|
||
|
|
...(place === 'bottom'
|
||
|
|
? { top: `${rect.bottom + 6}px` }
|
||
|
|
: { bottom: `${window.innerHeight - rect.top + 6}px` })
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function show() {
|
||
|
|
if (props.disabled || !props.content) return
|
||
|
|
window.clearTimeout(timer)
|
||
|
|
timer = window.setTimeout(() => {
|
||
|
|
visible.value = true
|
||
|
|
nextTick(measure)
|
||
|
|
}, props.delay)
|
||
|
|
}
|
||
|
|
|
||
|
|
function hide() {
|
||
|
|
window.clearTimeout(timer)
|
||
|
|
visible.value = false
|
||
|
|
}
|
||
|
|
|
||
|
|
onBeforeUnmount(() => window.clearTimeout(timer))
|
||
|
|
</script>
|
||
|
|
|
||
|
|
<template>
|
||
|
|
<span ref="rootRef" class="qk-tooltip" @mouseenter="show" @mouseleave="hide" @focusin="show" @focusout="hide">
|
||
|
|
<slot />
|
||
|
|
<Teleport to="body">
|
||
|
|
<span v-if="visible" class="qk-tooltip-pop" :style="style" role="tooltip">{{ content }}</span>
|
||
|
|
</Teleport>
|
||
|
|
</span>
|
||
|
|
</template>
|