我需要一些帮助。
我尝试使用相同的类(.section-container)定位多个 div 的 Y 坐标
但是 console.log 为每个 div 返回 0。
(2) [div.section-container, div.section-container] 2 0
你有什么想法吗?
const sectionSelector = element !== undefined
? element.querySelectorAll('.section-container')
: false;
const sectionArr = Array.from(sectionSelector);
const PosY = function()
{
sectionArr.forEach( function(e)
{
const pos = e.getBoundingClientRect();
const y = pos.top;
console.log(y)
})
}
PosY();
感谢您的帮助!
答案 0 :(得分:0)
您是否已经尝试过使用 pos.y 而不是 pos.top?
top 只是一个相对值,在 MDN (https://developer.mozilla.org/de/docs/Web/API/Element/getBoundingClientRect) 中描述
答案 1 :(得分:0)
就给出的代码而言,我看不出有什么问题,但我们没有 HTML,所以我添加了一些来测试。
只要有 HTML 代码,代码就可以正常工作。希望比较此代码段中的内容和您实际拥有的内容,可以对问题有所了解。
<style>
.section-container {
width: 200px;
height: 300px;
}
</style>
<div id="main">
<div class="section-container"></div>
<div class="section-container"></div>
<div class="section-container"></div>
<div class="section-container"></div>
<div class="section-container"></div>
</div>
<script>
let element = document.getElementById('main');
const sectionSelector = element !== undefined
? element.querySelectorAll('.section-container')
: false;
const sectionArr = Array.from(sectionSelector);
const PosY = function()
{
sectionArr.forEach( function(e)
{
const pos = e.getBoundingClientRect();
const y = pos.top;
console.log(y)
})
}
PosY();
</script>