2017-05-08 47 views
2

当父容器为position: fixed时,如果试图获取元素的垂直位置scrollTop,我有点困难。使用javascript获取元素在固定容器中的垂直位置

使用scrollTop时,输出值为0。我猜这是因为元素不再是严格的标准流程。有什么明显的我失踪或有没有不同的方式来做到这一点,保持position: fixed,而不使用jQuery。也许有一种方法可以获得元素的位置与父元素的关系吗?

我附上了下面的测试代码。

document.getElementById('target').scrollTop;
.container { 
 
    padding-top: 1200px; 
 
    position: fixed; 
 
    top: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    background-color: orange; 
 
} 
 

 
#element { 
 
    background-color: green; 
 
}
<div class="container"> 
 
    <div id="target"> 
 
    Target 
 
    </div> 
 
</div>

回答

2

您可能需要使用offsetTop代替。 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

HTMLElement.offsetTop只读属性返回当前元素相对于offsetParent节点顶部的距离。

console.log(document.getElementById('target').offsetTop);
.container { 
 
    padding-top: 1200px; 
 
    position: fixed; 
 
    top: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    background-color: orange; 
 
} 
 

 
#element { 
 
    background-color: green; 
 
}
<div class="container"> 
 
    <div id="target"> 
 
    Target 
 
    </div> 
 
</div>

+1

该死的那么简单:(谢谢 –

+0

@AdamHughes没有问题。 –

0

getBoundingClientRect什么?

Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。

document.getElementById('target').getBoundingClientRect().top;