我有一个垂直滚动的 div
元素。它包含带有文本的 span
元素。我怎样才能得到这些 span
元素的坐标。但我不希望它相对于滚动位置。
例如,在 div
中,假设它的宽度为 400px,高度为 1000px(但 View 高度为 500px),并且垂直滚动了一半。然后在 View 的中心,我看到一个文本,如果我点击它,我想要像 (200, 250) 这样的坐标
如何获取 div
容器的绝对坐标?
最佳答案
使用 element.getBoundingClientRect? (如果你想相对于容器,减去容器的顶部。)
function client() {
alert(document.getElementById('child').getBoundingClientRect().top);
}
function local() {
var container = document.getElementById('container');
var containerRect = container.getBoundingClientRect();
var child = document.getElementById('child');
var childRect = child.getBoundingClientRect();
localTop = childRect.top - containerRect.top;
alert(localTop);
}
#container {
height: 100px;
overflow:scroll;
border:1px solid red;
margin-top:100px;
}
#child {
background: yellow;
}
<div id="container">
<div>Test</div>
<div>Test</div><div>Test</div><div>Test</div><div>Test</div>
<div id="child">Item of interest</div>
<div>Test</div><div>Test</div><div>Test</div><div>Test</div>
</div>
<button onclick="client()">Global top</button>
<button onclick="local()">Local top</button>
关于javascript - 如何确定可滚动div中的元素坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429699/