通过 JS 与视口(非相对)相关的元素的位置坐标

Her*_*sen 1 javascript css vue.js vuejs2

我正在构建一个 vueJs 网络应用程序,我需要根据视口(而不是相对父元素)在我的网络应用程序中的元素位置。我想知道是否有这样做的功能/属性。

.offsetLeft不是我需要的,因为该元素位于具有position: relative的父元素内。

请查看我的笔:https : //codepen.io/mister-hansen/pen/aGdWMp (举个例子,什么不同的位置:相对。)

HTML

 <div id="app">
  <div class="box">
    <div class="box__in" ref="my_box_a">
      What is my position?
      <br> offsetLeft: <strong>{{posBoxA}}</strong>
    </div>

  </div>
  <div class="box box--relative">
    <div class="box__in" ref="my_box_b">
      What is my position in relative box?
      <br>
      offsetLeft: <strong>{{posBoxB}}?!</strong>
    </div>

  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JS - VueJs

const app = new Vue({
  el: '#app',
  data () {
    return {

      posBoxA: 0,
      posBoxB: 0,
      }
  },
  mounted () {
    this.calcPosOfBox()
  },
  methods: {
    calcPosOfBox () {
      this.posBoxA = this.$refs['my_box_a'].offsetLeft

      this.posBoxB = this.$refs['my_box_b'].offsetLeft

    }
  }
})
Run Code Online (Sandbox Code Playgroud)

社会保障局

html, body {
  margin: 0;
}

#app {
  padding: 10vh 100px;
  font-family: sans-serif;
}

.box {
  margin: 0 auto 10vh;
  padding: 10vh 50px;
  background: lightgrey;

  &--relative {
    border: 1px solid red;
    position: relative;
  }

  &__in {
    padding: 1rem;
    background: lightgreen;
  }
}
Run Code Online (Sandbox Code Playgroud)

zer*_*298 5

使用getBoundingClientRect(). 在xy收益相对于顶级的视口。

强调我的:

返回值是一个DOMRect对象,它是getClientRects()元素返回的矩形的并集,即与元素关联的 CSS 边框框。其结果是,其包含整个元件,与所述最小矩形只读lefttoprightbottomxywidth,和height描述在像素整体边界框属性。比其他属性widthheight 相对于左上视口

const app = new Vue({
  el: '#app',
  data() {
    return {

      posBoxA: 0,
      posBoxB: 0,
    }
  },
  mounted() {
    this.calcPosOfBox()
  },
  methods: {
    calcPosOfBox() {
      const boxABB = this.$refs["my_box_a"].getBoundingClientRect();
      const boxBBB = this.$refs["my_box_b"].getBoundingClientRect();
      this.posBoxA = boxABB.x;
      this.posBoxB = boxBBB.x;

    }
  }
})
Run Code Online (Sandbox Code Playgroud)
html,
body {
  margin: 0;
}

#app {
  padding: 10vh 100px;
  font-family: sans-serif;
}

.box {
  margin: 0 auto 10vh;
  padding: 10vh 50px;
  background: lightgrey;
}

.box--relative {
  border: 1px solid red;
  position: relative;
}

.box__in {
  padding: 1rem;
  background: lightgreen;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js"></script>
<div id="app">
  <div class="box">
    <div class="box__in" ref="my_box_a">
      What is my position?
      <br> offsetLeft: <strong>{{posBoxA}}</strong>
    </div>

  </div>
  <div class="box box--relative">
    <div class="box__in" ref="my_box_b">
      What is my position in relative box?
      <br> offsetLeft: <strong>{{posBoxB}}?!</strong>
    </div>

  </div>
</div>
Run Code Online (Sandbox Code Playgroud)