1、实现效果
提示框会跟随鼠标移动,如果超出显示边界,会自动计算贴着边界进行展示。
微信图片_20221107215200.png
2、具体代码(vue3写法)
<template>
<div class="recent-item" @mouseover="handleMouseOver" @mouseleave="handleMouseLeave">
<div>hover看效果</div>
<div
v-show="show"
ref="recentRef"
class="recent-item-tip"
:style="{ left: posX + 'px', top: posY + 'px', opacity: opacity }"
>
我是提示
</div>
</div>
</template>
<script setup lang="ts">
import { ref, nextTick } from 'vue';
/** 鼠标的位置x */
let posX = ref(0);
/** 鼠标的位置y */
let posY = ref(0);
/** 显示状态 */
let show = ref(false);
/** 透明度 */
let opacity = ref(0);
/** 当前组件dom */
const recentRef = ref<HTMLDivElement | null>(null);
const timer = ref(null);
/** 鼠标滑过时,取鼠标的位置 */
function handleMouseOver(e) {
/** 防抖执行更新数据 */
if (timer.value) {
clearTimeout(timer.value);
}
timer.value = setTimeout(() => {
/** 更新最近使用的列表 */
handleChangePos(e);
clearTimeout(timer.value);
}, 10);
}
/** 更改提示条的展示位置 */
function handleChangePos(e) {
show.value = true;
let clientHeight = document.documentElement.clientHeight;
let clientWidth = document.documentElement.clientWidth;
let pointX = e.clientX;
let pointY = e.clientY;
nextTick(() => {
// 内容的宽度和高度
let selfWidth = recentRef.value.clientWidth;
let selfHeight = 86;
// 判断有没有到容器的边界
if (pointX + selfWidth > clientWidth) {
pointX = clientWidth - selfWidth;
}
if (pointY + selfHeight > clientHeight) {
pointY = clientHeight - selfHeight;
}
posX.value = pointX;
posY.value = pointY;
opacity.value = 1;
});
}
/** 鼠标滑走时,隐藏tip */
function handleMouseLeave() {
posX.value = 0;
posY.value = 0;
show.value = false;
opacity.value = 0;
clearTimeout(timer.value);
timer.value = null;
}
</script>
<style lang="scss" scoped>
.recent-item {
text-align: center;
height: 60px;
line-height: 60px;
width: 100px;
cursor: pointer;
background: rgba(8, 48, 93, 0.04);
&:hover {
background: red;
}
.recent-item-tip {
position: fixed;
z-index: 999;
top: 0;
left: 0;
font-size: 12px;
padding: 5px;
line-height: 20px;
box-sizing: border-box;
word-break: keep-all;
background-color: #fff; // #fff
border: 1px solid #1113171a; // #1113171A
border-radius: 4px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.3);
opacity: 0;
}
}
</style>
网友评论