首页 > 其他分享 >鼠标是否在元素内

鼠标是否在元素内

时间:2022-10-14 11:24:22浏览次数:30  
标签:el obj 鼠标 是否 getBoundingClientRect 元素 Number let div

      let that = this
      // 判断鼠标是否落在一个块级元素内部
      function checkIn(obj, posx, posy) {
        let x = posx
        let y = posy

        let div_x = Number(obj.getBoundingClientRect().left) // obj相对屏幕的横坐标
        let div_x_width = Number(
          obj.getBoundingClientRect().left + obj.clientWidth
        ) // obj相对屏幕的横坐标+width

        let div_y = Number(obj.getBoundingClientRect().top) // obj相对屏幕的纵坐标
        let div_y_height = Number(
          obj.getBoundingClientRect().top + obj.clientHeight
        ) // obj相对屏幕的纵坐标+height

        if (x > div_x && x < div_x_width && y > div_y && y < div_y_height) {
          return true
        } else {
          return false
        }
      }
      document.addEventListener('click', (e) => {
        if (e.path[0].className === 'el-icon-more') {
        } else {
          let el = document.querySelector('.code-collection')
          if (checkIn(el, e.clientX, e.clientY)) {
            console.log('在元素内')
          } else {
            console.log('在元素外')
          }
        }
      })

 

标签:el,obj,鼠标,是否,getBoundingClientRect,元素,Number,let,div
From: https://www.cnblogs.com/ronle/p/16791029.html

相关文章