2016-05-16 84 views
0

下面的值是我的代碼:計算 「左」, 「頂」,從固定的位置浮動元素

HTML:

<div id="test"> 
This text is fixed in one spot 
</div> 

CSS:

#test{ 
    border:1px solid black; 
    position: fixed; 
    margin: 8px; 
    right: 0px; 
    bottom: 0px; 
    height: 200px; 
    width: 50%; 
    z-Index: 4; 
} 

到目前爲止我能在一個固定的位置製作一個盒子並使其正確顯示(高度爲200像素,寬度爲屏幕的50%)。當屏幕寬度發生變化時,寬度會發生變化,但我的問題是我想計算該框的左上像素位置,因爲我不希望框的任何部分出現在任何AdSense廣告單元的頂部。屏幕左側有我的廣告單元。

我在JavaScript試圖獲得這樣最左邊的像素框的值:

<script> 
alert(document.getElementById('test').left); 
alert(document.getElementById('test').style.left); 
</script> 

而且我沒有從任何消息框中的一個數字。我所得到的只是一個空白和「未定義」。

有沒有一種方法可以計算盒子的左上角像素位置,而不需要通過JavaScript定時器定期檢測值?

不,我不想使用Jquery。

+0

爲什麼不乾脆讓廣告的高度和位置是高度下面的框中? –

+0

無論用戶頁面有多遠,我都希望該框保留在右下角。 – Mike

回答

1

我認爲你在找什麼是offsetLeftoffsetTop方法。

alert(document.getElementById('test').offsetLeft); 
 
alert(document.getElementById('test').offsetTop);
#test{ 
 
    border:1px solid black; 
 
    position: fixed; 
 
    margin: 8px; 
 
    right: 0px; 
 
    bottom: 0px; 
 
    height: 200px; 
 
    width: 50%; 
 
    z-Index: 4; 
 
}
<div id="test"> 
 
This text is fixed in one spot 
 
</div>

+0

似乎在這裏工作。我希望它適用於所有瀏覽器。 – Mike