html
<template>
<div>
<div class="buttonbox">
<button @click="privewImage">图片预览</button>
<div class="box1" @mouseenter="goBox" ref="box1">
<p class="cursor" :style="{ left: `${eventX}px`, top: `${eventY}px` }" ref="lookDetail" v-if="isshow"> 查看详情</p>
</div>
</div>
<!-- <Prview :privewList="movieList" :privewIndex="index" ref="prview" v-if="isshow" @close="close" /> -->
</div>
</template>
js
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { topRatedMovies } from '@/api/index'
import _ from "lodash";
const prview = ref(null)
const lookDetail = ref(null)
const box1 = ref(null)
let data = reactive({
movieList: [],
isshow: false,
index: 0,
eventX: 0,
eventY: 0,
});
let { movieList, isshow, index, eventX, eventY } = toRefs(data);
onMounted(async () => {
let res = await topRatedMovies()
movieList.value = res.data.movieList.map(item => item.poster)
movieList.value.unshift("https://www.vifa.cn/resource/userfiles/fileupload/202303/1633734360076554240.m4v")
})
function goBox() {
isshow.value = true
box1.value.addEventListener("mousemove", move)
function move($event) {
let t = box1.value.getBoundingClientRect().top
let l = box1.value.getBoundingClientRect().left
let b = box1.value.getBoundingClientRect().bottom
let r = box1.value.getBoundingClientRect().right
let x = $event.pageX - l - lookDetail.value.offsetWidth / 2
let y = $event.pageY - t - lookDetail.value.offsetHeight / 2
if (x <= 0) x = 0
if (y <= 0) y = 0
if ($event.pageX > r - lookDetail.value.offsetWidth / 2) x = box1.value.getBoundingClientRect().width - lookDetail.value.offsetWidth
if ($event.pageY > b - lookDetail.value.offsetHeight / 2) y = box1.value.getBoundingClientRect().height - lookDetail.value.offsetHeight
eventX.value = x
eventY.value = y
}
box1.value.addEventListener("mouseleave", function () {
box1.value.removeEventListener("mousemove", move)
isshow.value=false
}, {
capture: false,
passive: false,
once: true
})
}
function privewImage() {
isshow.value = true
nextTick(() => {
prview.value.autoPlay()
})
}
function close() {
isshow.value = false
}
</script>
css
<style lang="less">
.buttonbox {
height: 120vh;
}
.box1 {
width: 450px;
height: 200px;
position: relative;
margin: 0 auto;
margin-top: 50px;
background: red;
p {
position: absolute;
background: white;
width: 100px;
height: 100px;
}
&:hover {
}
}
button {
width: 300px;
height: 100px;
font-size: 16px;
margin: 0 auto;
}
</style>