2013-01-11 23 views
1

當我問document.body.getBoundingClientRect().top;版Firefox 17.0.1上有沒有風格可言一個簡單的網站,它返回錯誤的值。我期望8,這是瀏覽器默認,但它給我21.4。然而,.left偏移量是正確的。Firefox的document.body.getBoundingClientRect()。top不正確?

在Chrome中的偏移量是正常工作,給我8兩個頂部和左側。

我重視的情況截圖,你可以看到,頂部不應該是22.4.Screenshot of the situation

下面是使用Firefox 18以下的HTML

<html><head> 
<title>Index</title> 
<style type="text/css"></style></head> 
<body> 
    <div> 
     <h1>Index</h1> 
     <p>This is the index. The site contains in total 4 sites without 
      any Javascript. They are linked using href links.</p> 
     <p>The site looks like this:</p> 
     <ul> 
      <li>Index ->; a</li> 
      <li>Index ->; b</li> 
      <li>b ->; c</li> 
      <li>c ->; b</li> 
      <li>c ->; Index</li> 
     </ul> 
    </div> 
    <a href="a.html">Go to A</a> 
    <a href="b.html">Go to B</a> 
</body></html> 
+0

問題也發生在Firefox 18.0 – Alex

回答

2

先給你<html>黃色背景和<body>綠色的背景,看看呈現的樣子。我敢打賭,這個綠色的矩形實際上是從視口頂部開始的22px。

發生這種情況的原因是,身體的8px頂部邊緣與<h1>的22 + px頂部邊緣一起摺疊,因爲這些邊緣相鄰。見http://www.w3.org/TR/CSS21/box.html#collapsing-margins

瀏覽器在標準模式完全相同的行爲。但是,在特殊模式(他什麼上面的HTML片段是其中),似乎做一些奇怪的地方仍然<h1>報告了21px上邊距但利潤率不與該<body>的崩潰..雖然上把一個上邊距<div>確實將其與身體摺疊。這是你的怪癖模式。

+0

你這個人!在Chrome中添加「<!DOCTYPE html>」顯示出問題。通過doctype聲明,'H1'下移到'21'的邊界。然而,Firefox將它渲染爲邊距爲8,但是「document.body.getBoundingClientRect()'返回一個不同的邊距是愚蠢的。 – Alex

+0

呃...... Firefox以什麼方式渲染邊界像是8?事實上,保證金是21.您是否嘗試按照我的建議添加背景? –

+0

哎呀,我在Chrome中做到了。現在,我看到Firefox確實呈現正確。如果沒有'<!DOCTYPE html>',Chrome是唯一不能正確呈現的。我的錯! – Alex

1

我剛剛試了一下代碼,我得到期望的值8(我清除了所有格式的清晰度,但它給出了相同的值8)。

<html> 
<head> 
<title>Index</title> 
<script> 
    window.onload = function() { 
     document.getElementById("getBoundingClientRectTop").innerHTML = document.body.getBoundingClientRect().top; 
    } 
</script> 
</head> 
<body> 
    <span id="getBoundingClientRectTop">???</span> 
</body> 
</html> 
+0

這是一個正確的答案,但不適合我,因爲我需要能夠從控制檯頁面中運行它,而不是使用Javascript。我用它與硒。 – Alex