js获取到的getBoundingClientRect()为负数是为什么?

新手上路,请多包涵

image.png
这个抓娃娃是爪子只往下面抓,娃娃往左边走。用的是swiper
但是当我在算爪子触碰到娃娃的时候出现了一个问题。是用getBoundingClientRect函数获取距离视口的边距,但由于娃娃是用swiper写的。他会超出屏幕,所获取到的left right全部为负数。

  <swiper :options="swiperOptions" class="dall_swiperBox" v-if="itemSwiper == 30">
<swiper-slide class="dall_swiperitem" v-for="(item, index) in dallList" :key="item">
 <div :style="{opacity: (index == dallIndex ? 0 : 1)}" :id="'dall_' + item">
<img :src="xqBgPath + dollImgConfigs.dall1" alt="" style="width:70px;height:70px" >
  </div>
</swiper-slide>
 </swiper>
                swiperOptions: {
                    loop: true,
                    slidesPerView: 3,
                    speed: 1000,
                    autoplay: {
                        delay: 0,
                    },
                    observer: true,
                    observeParents: true,
                },
      that.dallHideTimeout = setTimeout(_ => {
          let dallList = that.dallList || []
          dallList.forEach(item => {
              let id = 'dall_' + item 
              let rect = document.getElementById(id).getBoundingClientRect()
              console.log('rect', rect)
              let left = rect.left
              let height = rect.height
              let right = rect.right
              let minLeft = windowWidth / 2 - height * 1.15 
              let maxLeft = windowWidth / 2 + height * 1.15 
              if ((left >= minLeft) && (left <= maxLeft) && (right >= minLeft) && (right <= maxLeft)) {
                  that.dallIndex = item 
                  that.isCatch = true 
              }
          })
      }, moveDownTimer / 2);
阅读 3.3k
1 个回答

Element.getBoundingClientRect() 方法返回一个 DOMRect 对象,其提供了元素的大小及其相对于视口的位置。
元素在视窗外部,比如上方或者左侧,相对于视窗就是负数,

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏