点击div盒子外部,使这个盒子关闭
- 对盒子外部的区域添加点击事件监听,假定外部区域为整个页面,这里使用的是vue3框架
onMounted(() => {
document.addEventListener('click', setPopoverState)
})
onUnmounted(() => {
document.removeEventListener('click', setPopoverState)
})
- 触发监听事件之后,运行 setPopoverState 方法,当然,在这之前需要获取到要关闭的盒子,vue3使用 ref 可以获取到这个盒子。
const setPopoverState = (event: any) => {
disposeCommonContainerState(event, needCloseRef)
}
- 下面就是根据点击事件中的event参数的位置属性与盒子本身的getBoundingClientRect()方法获取到的位置信息进行比对。
Element.getBoundingClientRect()返回的是一个DomRect对象,其提供了元素的大小以及相对于视口的位置。
function disposeCommonContainerState(
event: PointerEvent,
ref_: Ref<HTMLDivElement | undefined>,
) {
if (ref_.value) {
const icon_bounding: DOMRect = ref_.value.getBoundingClientRect()
if (ref_.value?.children?.length > 1) {
const pop_bounding = ref_.value.children[1].getBoundingClientRect()
const x = event.x
const y = event.y
console.log(`点击横坐标---${x}---竖坐标---${y}`)
if (
!(
(y > icon_bounding.top &&
y < icon_bounding.bottom &&
x > icon_bounding.left &&
x < icon_bounding.right) ||
(y > pop_bounding.top &&
y < pop_bounding.bottom &&
x > pop_bounding.left &&
x < pop_bounding.right)
)
) {
console.log('关闭盒子')
}
}
}
}