<script>
export default {
name: 'Tooltip',
props: {
// 显示的内容
text: {
type: String,
default: ''
},
// 鼠标是否可进入到 tooltip 中
// 当 enterable=false,直接隐藏
// 当 enterable=true,判断鼠标移到的下一个元素是否还在 tooltip 内,如果不在就隐藏
enterable: {
type: Boolean,
default: false
}
},
data() {
return {
show: false
};
},
methods: {
showTooltip() {
const el = this.$slots.default[0].elm;
// 来判断 slot 里的文字是否出现省略号
if (el.clientWidth < el.scrollWidth) {
this.show = true;
}
},
hideTooltip(e) {
if (!this.enterable) {
this.show = false;
} else {
const tooltip = this.$el;
// 如果enterable是true 则鼠标是否可进入到 tooltip 中
if (!tooltip.contains(e.relatedTarget)) {
this.show = true;
}
}
}
}
};
</script>
<template>
<div
:class="['ud-tooltip', {show: show}]"
@mouseenter="showTooltip"
@mouseleave="hideTooltip"
>
<div v-if="show && text" class="ud-tooltip-text">{{ text }}</div>
<slot></slot>
</div>
</template>
<style lang="scss" scoped>
.ud-tooltip {
&-text { opacity: 0; position: absolute; padding: 4px 8px; border-radius: 4px; left: 50%; transform: translateX(-50%); background-color: rgba($color: #000000, $alpha: .65);
color: #fff; white-space: nowrap; height: auto; line-height: 18px; margin: -30px 0 0 6px; transition: all .15s; z-index: 99999;
&::before { position: absolute; content: ""; bottom: -3px; margin-left: -4px; left: 50%; transform: rotate(-45deg); width: 0;
height: 0; border-top: 5px solid transparent; border-right: 5px solid transparent; border-right: 5px solid transparent;
border-bottom: 5px solid rgba($color: #000000, $alpha: .65);
}
}
&:hover {
.ud-tooltip-text { opacity: 1;}
}
}
</style>
文字溢出后才展示Tooltip
最新推荐文章于 2024-06-04 17:26:23 发布