2017-05-08 10 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; 
関連する問題