如何点击一个div盒子之外的部分,使这个div盒子关闭

点击div盒子外部,使这个盒子关闭

  1. 对盒子外部的区域添加点击事件监听,假定外部区域为整个页面,这里使用的是vue3框架
 onMounted(() => {
     document.addEventListener('click', setPopoverState)
  })
  onUnmounted(() => {
   document.removeEventListener('click', setPopoverState)
  })
  1. 触发监听事件之后,运行 setPopoverState 方法,当然,在这之前需要获取到要关闭的盒子,vue3使用 ref 可以获取到这个盒子。
const setPopoverState = (event: any) => {
   	  disposeCommonContainerState(event, needCloseRef)
  }
  1. 下面就是根据点击事件中的event参数的位置属性与盒子本身的getBoundingClientRect()方法获取到的位置信息进行比对。
    Element.getBoundingClientRect()返回的是一个DomRect对象,其提供了元素的大小以及相对于视口的位置。
function disposeCommonContainerState(
    event: PointerEvent,
    ref_: Ref<HTMLDivElement | undefined>,
  ) {
    if (ref_.value) {
      // console.log(event, ref_.value.children[1].getBoundingClientRect())
      // 图标
      const icon_bounding: DOMRect = ref_.value.getBoundingClientRect()
      // 二次判断 子元素中的popContainer
      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('关闭盒子')
        }
      }
    }
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值