2012-09-11 18 views
2

因此,在一個簡單的頁面中,有一個div包含一個img。該文件可能與image的高度相同。然而,這種情況並非如此。該文件稍大,取決於環境。看到這個jsfiddle看到一個例子。基本上,如果將圖像設置爲文檔高度,則文檔高度會發生變化。爲什麼更改此圖像的高度等於文檔的高度會失敗?

萬一的jsfiddle不再可用,這裏是設置:

HTML

<div><img id="img" src="http://images.nationalgeographic.com/wpf/media-live/photos/000/138/overrides/save-the-ocean-tips_13821_600x450.jpg" /></div>​ 

JS

$(function(){ 
alert("Image Height Before Assignment: " + $("#img").height()); 
var docH = $(document).height(); 
alert("Document Height Before Assignment: " + docH); 
$("#img").height(docH); 
alert("Image Height After Assignment: " + $("#img").height()); 
alert("Document Height After Assignment: " + $(document).height()); 
}); 

爲什麼不能像這樣將圖像設置爲文檔高度,而​​不更改文檔高度?

如何在不更改文檔高度的情況下將圖像設置爲文檔高度?

+0

請注意,jsfiddles不會持續,所以這個問題將變得毫無意義。 –

+1

@LeeTaylor - 發佈元,如果你有一個問題與jsfiddle。 –

+0

這是對jsfiddle的一種常見批評。允許問題和答案在將來使用。 –

回答

2

我有固定的,通過添加align="absmiddle"到圖像

Demo here

+0

這是行不通的,但有沒有更標準化的做法呢? –

+0

我嘗試過'vertical-align:middle',但它沒有爲我工作,這就是爲什麼我建議這個解決方案 – haynar

1

它有事情做與HTML DTD。當我將其更改爲HTML 4.01 Transitional時,所有警報都給出相同的值。如您所說,HTML 5HTML 4.01 Strict都會更改文檔高度。

'希望這有助於追查原因。

-1

我建議你創建一個這樣的CSS從身體

body{ 
margin:0px; 
paddin:0px; 
border:0px; 
} 

body標籤都有自己的proprety去除所有多餘的。

0

使用align="absmiddle"是不好的形式和非標準化。我已經要求haynar1658更改他的答案,以反映我找到的解決方案,因爲我正在尋找align="absmiddle"的更爲標準化的版本。我遇到的是CSS屬性vertical-align:middle;。以下是jsfiddle的解決方案。

對於那些誰害怕或的jsfiddle的關鍵,這裏是代碼:

HTML

<div><img id="img" src="http://images.nationalgeographic.com/wpf/media-live/photos/000/138/overrides/save-the-ocean-tips_13821_600x450.jpg" /></div>​ 

CSS

/* 
This will ensure the document height doesn't change 
*/ 

#img 
{ 
vertical-align:middle; 
}​ 

JS

//Display Image height, then document height, then change image height and show that the change no longer affects the document height 
$(function(){ 
//Show Image height before 
alert("Image Height Before Assignment: " + $("#img").height()); 

//Get Document Height 
var docH = $(document).height(); 
//Show Document Height 
alert("Document Height Before Assignment: " + docH); 
//Assign image height 
$("#img").height(docH); 
//Show image height 
alert("Image Height After Assignment: " + $("#img").height()); 
//Show document height 
alert("Document Height After Assignment: " + $(document).height()); 
}); 

相關問題