我正在构建一个 vueJs 网络应用程序,我需要根据视口(viewport)(而不是相对父元素)在我的网络应用程序中定位一个元素。我想知道是否有函数/属性在执行此操作。
.offsetLeft 不是我需要的,因为该元素位于父元素内,position: relative。
请查看我的笔:https://codepen.io/mister-hansen/pen/aGdWMp (以不同的 position: relative 为例。)
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>
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
}
}
})
SCSS
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;
}
}
最佳答案
使用getBoundingClientRect()
. x
和 y
返回相对于顶级视口(viewport)。
强调我的:
The returned value is a
DOMRect
object which is the union of the rectangles returned bygetClientRects()
for the element, i.e., the CSS border-boxes associated with the element. The result is the smallest rectangle which contains the entire element, with read-onlyleft
,top
,right
,bottom
,x
,y
,width
, andheight
properties describing the overall border-box in pixels. Properties other thanwidth
andheight
are relative to the top-left of the viewport.
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;
}
}
})
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;
}
<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>
关于javascript - 通过 JS 与视口(viewport)(非相对)相关的元素的位置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49983893/