效果如下
<template>
<div class="home_itemWrap_map">
<div id="svgTemplateByWindPv">
<div class="sbBox">一个盒子</div>
<div class="sbBox">一个盒子</div>
<div class="sbBox">一个盒子</div>
</div>
<div id="fuHeBox_dq" class="fuHeBox_dq">弹窗移动</div>
</div>
</template>
<script>
export default {
name: 'MapWrap',
components: {},
data() {
return {
tanChuangStatus: false
}
},
computed: {},
mounted() {
this.setAtributeToEl()
},
methods: {
// 给元素 增加 事件 移入移出 点击等
setAtributeToEl() {
let _this = this
// 找到 所有的 svg设备标签 并添加移入事件
const wrappers = document.querySelectorAll('.sbBox')
wrappers.forEach(function(wrapper) {
wrapper.addEventListener('mouseenter', function(event) {
_this.tanChuangStatus = true
_this.setPosition(event)
})
// 鼠标持续移动
wrapper.addEventListener('mousemove', function(event) {
_this.tanChuangStatus = true
_this.setPosition(event)
})
// 鼠标移出
wrapper.addEventListener('mouseleave', function(event) {
_this.tanChuangHidden()
})
})
},
// 弹窗 移入显示 初始化位置
setPosition(e) {
const trigger = document.getElementById('svgTemplateByWindPv')
const popup = document.getElementById('fuHeBox_dq')
if (!this.tanChuangStatus) return
const rect = trigger.getBoundingClientRect()
const x = e.clientX - rect.left - popup.offsetWidth / 2 // 计算左侧偏移
const y = e.clientY - rect.top - popup.offsetHeight // 计算顶部偏移,可根据需要调整
// 防止弹窗移出视窗
const maxX = window.innerWidth - popup.offsetWidth
const maxY = window.innerHeight - popup.offsetHeight
popup.style.display = 'block'
popup.style.opacity = 1
popup.style.left = Math.max(0, Math.min(x, maxX)) + 'px'
popup.style.top = Math.max(0, Math.min(y, maxY)) + 'px'
},
// 移出关闭弹窗
tanChuangHidden() {
this.tanChuangStatus = false
let classPop = document.getElementsByClassName('fuHeBox_dq')[0]
classPop.style.opacity = 0
classPop.style.display = 'none'
// 移除mousemove事件监听器
document.removeEventListener('mousemove', this.updatePosition)
}
}
}
</script>
<style lang="scss" scoped>
.home_itemWrap_map {
width: 100%;
height: 100%;
padding: 12px;
background-color: black;
color: #ffffff;
position: relative;
overflow: hidden;
#svgTemplateByWindPv {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.sbBox {
width: 100px;
height: 32px;
background-color: blue;
cursor: pointer;
line-height: 32px;
text-align: center;
margin-right: 20px;
}
}
.fuHeBox_dq {
position: absolute;
z-index: 300;
width: 288px;
height: 130px;
padding: 15px 15px 15px 80px;
display: none;
opacity: 0;
transition: opacity 0.5s;
}
}
</style>